Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string into only two parts with a given character in Ruby?

Tags:

string

split

ruby

Our application is mining names from people using Twitter to login.

Twitter is providing full names in a single string.

Examples

1. "Froederick Frankenstien" 2. "Ludwig Van Beethoven" 3. "Anne Frank" 

I'd like to split the string into only two vars (first and last) based on the first " " (space) found.

Example    First Name    Last Name  1          Froederick    Frankenstein 2          Ludwig        Van Beethoven 3          Anne          Frank 

I'm familiar with String#split but I'm not sure how to only split once. The most Ruby-Way™ (elegant) answer will be accepted.

like image 652
Mulan Avatar asked Mar 09 '11 23:03

Mulan


People also ask

How do you split a string into two parts in Ruby?

Ruby – String split() Method with ExamplesIf pattern is a Regular Expression or a string, str is divided where the pattern matches. Parameters: arr is the list, str is the string, pattern is the either string or regExp, and limit is the maximum entries into the array. Returns: Array of strings based on the parameters.

How do you split a string at a certain character?

To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.

How do I split a string into substring?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


1 Answers

String#split takes a second argument, the limit.

str.split(' ', 2) 

should do the trick.

like image 52
yan Avatar answered Sep 23 '22 12:09

yan