tags:

views:

1084

answers:

6

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

when I use

ex.split(",").first

it returns

"test1"

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

ex.split(",").last

it returns only

"test5"

how to get the remaining items skipping first one?

+10  A: 

Try this:

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

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

avdgaag
In what version of Ruby? I tried it in 1.8.7 and `rest` only contains "test2".
Jonas Elfström
probably meant `first,*rest = ex.split(/,/)`
ezpz
Yep, I could not test my line at the time. `first, *rest = ex.split(/,/)` was indeed what I meant. Thanks for clearing that up.
avdgaag
+5  A: 

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

rest = ex.slice(1 .. -1)
# or
rest = ex[1 .. -1]
Konrad Rudolph
So with a string you'd want `ex.split(/, /).slice(1..-1)` to get all but the first elements, assuming you're not interested in the first value.
avdgaag
+4  A: 

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

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

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

array = string.split(/, /)

And in the end you only need all the elements excluding 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 ?

bltxd
+3  A: 
ex="test1,test2,test3,test4,test5"
all_but_first=ex.split(/,/)[1..-1]
Jonas Elfström
+4  A: 

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

The 2 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"]

ChaosR
Downside is you'd have to `split` again if you want all but the first values as an array rather than a string. Still a nice trick.Also, using `ex.split(',', 2).last` would not return the array you mention, only its last value, right?
avdgaag
Copy-Paste mistake haha, fixed it
ChaosR
A: 

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

parameter1,parameter2,parameter3,parameter4,parameter5 = ex.split(",")
Raafat