我有长度 ~ 700的文本。如何获得它的第一个字符的 ~ 30?
如果文本在 your_text变量中,则可以使用:
your_text
your_text[0..29]
使用 String#slice,也别名为 []。
String#slice
[]
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
由于您将其标记为 Rails,因此可以使用 truncate:
Http://api.rubyonrails.org/classes/actionview/helpers/texthelper.html#method-i-truncate
例如:
truncate(@text, :length => 17)
摘录也不错,它可以让你显示文本的摘录,如下:
excerpt('This is an example', 'an', :radius => 5) # => ...s is an exam...
Http://api.rubyonrails.org/classes/actionview/helpers/texthelper.html#method-i-excerpt
如果你想要一个字符串,那么其他的答案是可以的,但是如果你想要的是前几个字母作为字符,那么你可以把它们作为一个列表来访问:
your_text.chars.take(30)
如果你在 铁轨中需要它,你可以使用 第一(源代码)
'1234567890'.first(5) # => "12345"
还有 最后(源代码)
'1234567890'.last(2) # => "90"
或检查 由/往(源代码) :
"hello".from(1).to(-2) # => "ell"