Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

split

ruby

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 all the remaining items skipping first one?

like image 376
sgi Avatar asked Aug 26 '09 09:08

sgi


People also ask

How do I split a string into multiple parts?

Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.

How do you split a string on first occurrence?

To split a JavaScript string only on the first occurrence of a character, call the slice() method on the string, passing it the index of the character + 1 as a parameter. The slice method will return the portion of the string after the first occurrence of the character.

How do you split text in Ruby?

split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.


1 Answers

Try this:

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

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

like image 136
avdgaag Avatar answered Sep 29 '22 03:09

avdgaag