Leo
Leo

Reputation: 2103

How do I print an exact number of characters from :text?

I have a list of objects, with one attribue of :text. I want to print only the first 250 characters of each :text.

Is there any simple way in Rails to do it?

Here's how im doing my iteration:

[email protected] do |c|
        %tr
          %td= c.id
          %td= c.description
          %td

Where, description is text.

Upvotes: 2

Views: 214

Answers (2)

nicosantangelo
nicosantangelo

Reputation: 13716

You can use truncate:

c.description.truncate(250, :separator => ' ')

It will add "..." automatically for you, and you have the separator option so you don't have to worry about words being chopped in the middle.

Upvotes: 5

hdgarrood
hdgarrood

Reputation: 2151

Yep, it's just normal Ruby code:

%td= c.description[0..249]

string[n..m] will give you a substring of string, starting with the nth element, and ending with the mth. see http://ruby-doc.org/core-2.0/String.html#method-i-5B-5D

Although perhaps you should consider whether this code might be better off in your model than in the view?

Upvotes: 3

Related Questions