开发者

How to get a substring of text?

开发者 https://www.devze.com 2023-03-09 04:19 出处:网络
I have text with length ~700. How do I get only ~开发者_如何学编程30 of its first characters?If you have your text in your_text variable, you can use:

I have text with length ~700. How do I get only ~开发者_如何学编程30 of its first characters?


If you have your text in your_text variable, you can use:

your_text[0..29]


Use String#slice, also aliased as [].

a = "hello there"
a[1]                   #=> "e"
a[1,3]                 #=> "ell"
a[1..3]                #=> "ell"
a[6..-1]               #=> "there"
a[6..]                 #=> "there" (requires Ruby 2.6+)
a[-3,2]                #=> "er"
a[-4..-2]              #=> "her"
a[12..-1]              #=> nil
a[-2..-4]              #=> ""
a[/[aeiou](.)\1/]      #=> "ell"
a[/[aeiou](.)\1/, 0]   #=> "ell"
a[/[aeiou](.)\1/, 1]   #=> "l"
a[/[aeiou](.)\1/, 2]   #=> nil
a["lo"]                #=> "lo"
a["bye"]               #=> nil


Since you tagged it Rails, you can use truncate:

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-truncate

Example:

 truncate(@text, :length => 17)

Excerpt is nice to know too, it lets you display an excerpt of a text Like so:

 excerpt('This is an example', 'an', :radius => 5)
 # => ...s is an exam...

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-excerpt


if you need it in rails you can use first (source code)

'1234567890'.first(5) # => "12345"

there is also last (source code)

'1234567890'.last(2) # => "90"

alternatively check from/to (source code):

"hello".from(1).to(-2) # => "ell"


If you want a string, then the other answers are fine, but if what you're looking for is the first few letters as characters you can access them as a list:

your_text.chars.take(30)
0

精彩评论

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