ruby 如何将字符串拆分为多个单词的数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15914614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:52:36  来源:igfitidea点击:

How do I split string into array of multiple words?

rubystring

提问by sharataka

I have a string that I'm using .split(' ') on to split up the string into an array of words. Can I use a similar method to split the string into an array of 2 words instead?

我有一个字符串,我正在使用 .split(' ') 将字符串拆分为一个单词数组。我可以使用类似的方法将字符串拆分为 2 个单词的数组吗?

Returns an array where each element is one word:

返回一个数组,其中每个元素都是一个单词:

words = string.split(' ')

I'm looking to return an array where each element is 2 words instead.

我希望返回一个数组,其中每个元素都是 2 个单词。

采纳答案by Frambot

str = 'one two three four five six seven'
str.split.each_slice(2).map{|a|a.join ' '}
=> ["one two", "three four", "five six", "seven"]

This also handles the case of an odd number of words.

这也处理奇数个单词的情况。

回答by oldergod

You can do

你可以做

string= 'one1! two2@ three3# four4$ five5% six6^ sev'
string.scan(/\S+ ?\S*/)
# => ["one1! two2@", "three3# four4$", "five5% six6^", "sev"]

回答by Hew Wolff

Something like this should work:

这样的事情应该工作:

string.scan(/\w+ \w+/)

回答by the Tin Man

Ruby's scanis useful for this:

Rubyscan对此很有用:

'a b c'.scan(/\w+(?:\s+\w+)?/)
=> ["a b", "c"]

'a b c d e f g'.scan(/\w+(?:\s+\w+)?/)
=> ["a b", "c d", "e f", "g"]

回答by Piece Digital

This is all I had to do:

这就是我所要做的:

def first_word
    chat = "I love Ruby"
    chat = chat.split(" ")
    chat[0]
end