user646560
user646560

Reputation:

Ruby: How do I retrieve part of a string?

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

Answers (5)

the Tin Man
the Tin Man

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

Mark
Mark

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

Hck
Hck

Reputation: 9167

my_string.slice!(40..-1)

You can check description for slice! here

Upvotes: 0

J-_-L
J-_-L

Reputation: 9177

simply sub-string your string:

mystring[0...40]

Upvotes: 21

Andrew Haines
Andrew Haines

Reputation: 6644

You could do:

my_string[0..39]

Upvotes: 4

Related Questions