【发布时间】:2011-09-05 07:06:03
【问题描述】:
我的文本长度约为 700。我怎样才能只得到它的前 30 个字符?
【问题讨论】:
标签: ruby
我的文本长度约为 700。我怎样才能只得到它的前 30 个字符?
【问题讨论】:
标签: ruby
使用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
【讨论】:
-1 用于到达字符串的末尾,所以 a[1..-1] #=> "ello there".
a[-4,-2]。唯一有效的符号是两个点:a[-4..-2]。艰难地学会了它。
如果您在 rails 中需要它,您可以使用 first (source code)
'1234567890'.first(5) # => "12345"
还有last(source code)
'1234567890'.last(2) # => "90"
或者检查from/to (source code):
"hello".from(1).to(-2) # => "ell"
【讨论】:
NoMethodError: undefined method `first' for "abcde":String ,这是一个rails实现吗?
如果您想要一个字符串,那么其他答案都可以,但如果您要查找的是前几个字母作为字符,您可以将它们作为列表访问:
your_text.chars.take(30)
【讨论】:
既然你把它标记为 Rails,你可以使用 truncate:
http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-truncate
例子:
truncate(@text, :length => 17)
Excerpt 也很高兴知道,它可以让您显示文本的摘录,如下所示:
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 变量中,您可以使用:
your_text[0..29]
【讨论】: