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

String ex="test1, test2, test3, test4, test5"

when i use

 ex.split(",").first 

he returns

 "test1" 

Now I want to get the remaining elements, i.e. `" test2, test3, test4, test5 ". If i use

 ex.split(",").last 

he returns only

 "test5" 

How to transfer all remaining objects?

+66
string split ruby
Aug 26 '09 at 9:06
source share
8 answers

Try the following:

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

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

+82
Aug 26 '09 at 9:10
source share
 ex.split(',', 2).last 

2 at the end says: divide into 2 parts, no more.

a normal split will reduce the value by as many parts as it can, using a second value that you can limit how many pieces you get. Using ex.split(',', 2) will give you:

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

as an array, not:

 ["test1", "test2", "test3", "test4", "test5"] 
+37
Aug 26 '09 at 9:36
source share

Since you have an array, you really want Array#slice , not split .

 rest = ex.slice(1 .. -1) # or rest = ex[1 .. -1] 
+14
Aug 26 '09 at 9:16
source share

You are probably mistaken. From what I am collecting, you start with a line, for example:

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

Then you want to split it to save only meaningful substrings:

 array = string.split(/, /) 

And in the end, you only need all the elements except the first:

 # 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 

Is this the answer to your question?

+9
Aug 26 '09 at 9:16
source share
 ex="test1,test2,test3,test4,test5" all_but_first=ex.split(/,/)[1..-1] 
+5
Aug 26 '09 at 9:21
source share

Sorry a little late to the party and a little surprised that no one mentioned the drop method:

 ex="test1, test2, test3, test4, test5" ex.split(",").drop(1).join(",") => "test2,test3,test4,test5" 
+5
Apr 24 '13 at
source share

if you want to use them as an u array that you already knew, otherwise you can use each of them as another parameter ... try the following:

 parameter1,parameter2,parameter3,parameter4,parameter5 = ex.split(",") 
+4
Aug 26 '09 at 12:56
source share

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 
+2
Dec 19 '14 at 20:02
source share



All Articles