开发者

Ruby: How do I retrieve part of a string?

开发者 https://www.devze.com 2023-03-08 07:13 出处:网络
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

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?


simply sub-string your string:

mystring[0...40]


You could do:

my_string[0..39]


my_string.slice!(40..-1)

You can check description for slice! here


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..."


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"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号