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

Our application is the names of companies using Twitter to log in.

Twitter provides full names on one line.

Examples

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

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

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

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

+51
string split ruby
Mar 09 2018-11-11T00:
source share
4 answers

The line # split takes a second argument, the limit.

 str.split(' ', 2) 

gotta do the trick.

+125
Mar 09 '11 at 23:11
source share
 "Ludwig Van Beethoven".split(' ', 2) 

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

You can also do:

 "Ludwig Van Beethoven".partition(" ") 
+12
Mar 09 '11 at 23:11
source share

The second argument .split() indicates how many partitions to do:

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

And the conclusion:

 >> ruby -e "print 'one two three four five'.split(' ', 2)" >> ["one", "two three four five"] 
+8
Mar 09 '11 at 23:14
source share

Alternative:

  first= s.match(" ").pre_match rest = s.match(" ").post_match 
+7
Apr 12 '13 at 8:37
source share



All Articles