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

RubyStringSplit

Ruby Problem Overview


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.

Ruby Solutions


Solution 1 - Ruby

String#split takes a second argument, the limit.

str.split(' ', 2)

should do the trick.

Solution 2 - Ruby

"Ludwig Van Beethoven".split(' ', 2)

The second parameter limits the number you want to split it into.

You can also do:

"Ludwig Van Beethoven".partition(" ")

Solution 3 - Ruby

The second argument of .split() specifies how many splits to do:

'one two three four five'.split(' ', 2)

And the output:

>> ruby -e "print 'one two three four five'.split(' ', 2)"
>> ["one", "two three four five"]

Solution 4 - Ruby

Alternative:

    first= s.match(" ").pre_match
    rest = s.match(" ").post_match

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMulanView Question on Stackoverflow
Solution 1 - RubyyanView Answer on Stackoverflow
Solution 2 - RubysawaView Answer on Stackoverflow
Solution 3 - RubyBlenderView Answer on Stackoverflow
Solution 4 - RubyAnno2001View Answer on Stackoverflow