Reputation:
I want a way to only display a set number of characters from a string/text value.
I want it to work in a way that if my_string.length > 40
then only get first 40 characters from my_string
?
Upvotes: 12
Views: 12210
Reputation: 160621
Ruby lets you slice a string:
my_string = my_string[0, 40] if (my_string.length > 40)
As Andy H reminded me, this can be shorted to:
my_string = my_string[0, 40]
Here's an example:
str = '1234567890' * 5 #=> "12345678901234567890123456789012345678901234567890"
str[0, 40] #=> "1234567890123456789012345678901234567890"
Upvotes: 1
Reputation: 1068
If you are already using the activesupport gem (or if you don't mind adding it as a dependency), then you can also use String#truncate. If your string is longer than the set limit you will see "Your string..."
Upvotes: 1