Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split string into array of multiple words?

Tags:

string

ruby

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.

like image 935
sharataka Avatar asked Apr 09 '13 23:04

sharataka


People also ask

How do you split a string into an array of words?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you break a string into multiple parts?

As the name suggests, a Java String Split() method is used to decompose or split the invoking Java String into parts and return the Array. Each part or item of an Array is delimited by the delimiters(“”, “ ”, \\) or regular expression that we have passed. The return type of Split is an Array of type Strings.

Can split () take multiple arguments?

split() method accepts two arguments. The first optional argument is separator , which specifies what kind of separator to use for splitting the string. If this argument is not provided, the default value is any whitespace, meaning the string will split whenever .


1 Answers

Ruby's scan is useful for this:

'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"]
like image 125
the Tin Man Avatar answered Sep 20 '22 12:09

the Tin Man