How to split string into only two parts with a given character in Ruby? How to split string into only two parts with a given character in Ruby? ruby ruby

How to split string into only two parts with a given character in Ruby?


String#split takes a second argument, the limit.

str.split(' ', 2)

should do the trick.


"Ludwig Van Beethoven".split(' ', 2)

The second parameter limits the number you want to split it into.

You can also do:

"Ludwig Van Beethoven".partition(" ")


The second argument of .split() specifies how many splits to do:

'one two three four five'.split(' ', 2)

And the output:

>> ruby -e "print 'one two three four five'.split(' ', 2)">> ["one", "two three four five"]