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

Accepted answer
Score: 99

Try this:

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

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

Score: 43
ex.split(',', 2).last

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

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

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

as an array, instead 1 of:

["test1", "test2", "test3", "test4", "test5"]
Score: 15

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

rest = ex.slice(1 .. -1)
# or
rest = ex[1 .. -1]
Score: 9

You probably mistyped a few things. From 6 what I gather, you start with a string such 5 as:

string = "test1, test2, test3, test4, test5"

Then you want to split it to keep only 4 the significant substrings:

array = string.split(/, /)

And in the end 3 you only need all the elements excluding 2 the first one:

# We extract and remove the first element from array
first_element = array.shift

# Now array contains the expected result, you can check it with
puts array.inspect

Did that answer your question 1 ?

Score: 8

Sorry a bit late to the party and a bit 1 surprised that nobody mentioned the drop method:

ex="test1, test2, test3, test4, test5"
ex.split(",").drop(1).join(",")
=> "test2,test3,test4,test5"
Score: 6
ex="test1,test2,test3,test4,test5"
all_but_first=ex.split(/,/)[1..-1]

0

Score: 5

if u want to use them as an array u already 2 knew, else u can use every one of them as 1 a different parameter ... try this :

parameter1,parameter2,parameter3,parameter4,parameter5 = ex.split(",")
Score: 2

You can also do this:

String is ex="test1, test2, test3, test4, test5"
array = ex.split(/,/)
array.size.times do |i|
  p array[i]
end 

0

Score: 0

Try split(",")[i] where i is the index in result array. split gives 2 array below

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

whose element can be accessed 1 by index.

More Related questions