How to split a string in Ruby and get all items except the first one? How to split a string in Ruby and get all items except the first one? ruby ruby

How to split a string in Ruby and get all items except the first one?


Try this:

first, *rest = ex.split(/, /)

Now first will be the first value, rest will be the rest of the array.


ex.split(',', 2).last

The 2 at the end says: split into 2 pieces, not more.

normally split will cut the value into as many pieces as it can, using a second value you can limit how many pieces you will get. Using ex.split(',', 2) will give you:

["test1", "test2, test3, test4, test5"]

as an array, instead of:

["test1", "test2", "test3", "test4", "test5"]


Since you've got an array, what you really want is Array#slice, not split.

rest = ex.slice(1 .. -1)# orrest = ex[1 .. -1]