Ruby – How to split string into array of multiple words

rubystring

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?

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.

Best Answer

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.