I'm working in Ruby on Rails with Ruby 1.9.3 and Rails 3.2. I have a long string of words like this:
我在Ruby on Rails与Ruby 1.9.3和Rails 3.2一起工作。我有一长串这样的词:
foo bar banana nut fruit bar foobar cool awesome stack overflow
foobar banana nut fruit bar foobar cool awesome stack overflow
I'd like to divide this string into an array. Each element of the array should contain three words out of this string. How would I go about doing this?
我想把这个字符串分成一个数组。数组的每个元素都应该包含这个字符串中的三个单词。我该怎么做呢?
Thanks!
谢谢!
3 个解决方案
#1
11
o = str.split.each_slice(3).map{|a| a.join(" ")}
#2
4
string = "foo bar banana nut fruit bar foobar cool awesome stack overflow"
This will return an array where each item contains exactly three words from the string:
这将返回一个数组,其中每个条目恰好包含字符串中的三个单词:
string.scan /\w+\s+\w+\s+\w+/
# => ["foo bar banana", "nut fruit bar", "foobar cool awesome"]
If you want the remaining words in an item added to the end as well:
如果你想要在一个项目的剩余词也添加到结尾:
string.scan /\w+\s*\w*\s*\w*/
# => ["foo bar banana", "nut fruit bar", "foobar cool awesome", "stack overflow"]
#3
2
For your given example
你给的例子
x = "foo bar banana nut fruit bar foobar cool awesome stack overflow"
The code:
代码:
result = x.split(/\s+/).each_slice(3).to_a
will group them like:
将它们分组:
[ [foo, bar, banana] [nut, fruit, bar], [foobar, cool, awesome], [stack, overflow] ]
#1
11
o = str.split.each_slice(3).map{|a| a.join(" ")}
#2
4
string = "foo bar banana nut fruit bar foobar cool awesome stack overflow"
This will return an array where each item contains exactly three words from the string:
这将返回一个数组,其中每个条目恰好包含字符串中的三个单词:
string.scan /\w+\s+\w+\s+\w+/
# => ["foo bar banana", "nut fruit bar", "foobar cool awesome"]
If you want the remaining words in an item added to the end as well:
如果你想要在一个项目的剩余词也添加到结尾:
string.scan /\w+\s*\w*\s*\w*/
# => ["foo bar banana", "nut fruit bar", "foobar cool awesome", "stack overflow"]
#3
2
For your given example
你给的例子
x = "foo bar banana nut fruit bar foobar cool awesome stack overflow"
The code:
代码:
result = x.split(/\s+/).each_slice(3).to_a
will group them like:
将它们分组:
[ [foo, bar, banana] [nut, fruit, bar], [foobar, cool, awesome], [stack, overflow] ]