Ruby splits String into two parts and places a hash with predefined keys

I don't know if this is really good ruby ​​code, but what I'm trying to do is split the String into two separate sections and put the two values ​​in two special keys. For instance:

name_a = "Henry Fillenger".split(/\s+/,2) name = {:first_name => name_a[0], :last_name => name_a[1]} 

I was wondering if this can be done on one line using ruby ​​magic.

+4
source share
3 answers

You can use Hash[] and zip to do this:

 name = Hash[ [:first_name, :last_name].zip("Henry Fillenger".split(/\s+/,2)) ] 

However, I would say that your version is more readable. Not everything should be on the same line.

+15
source

Two more lines, but somewhat more readable, in my opinion,

 first_name, last_name = "Henry Fillenger".split(/\s+/,2) name = {:first_name => first_name, :last_name => last_name} 
+7
source

Just for fun, a non-split option (which is also two lines):

 m = "Henry Fillenger".match(/(?<first_name>\S+)\s+(?<last_name>\S+)/) name = m.names.each_with_object({ }) { |name, h| h[name.to_sym] = m[name] } 

The interesting parts will be the named capture groups ( (?<first_name>...) ) in the regular expression and the general hash method using each_with_object named capture groups require 1.9, though.

If someone dared, it would be possible to defuse the each_with_object bit directly in MatchData as, say, to_hash :

 class MatchData def to_hash names.each_with_object({ }) { |name, h| h[name.to_sym] = self[name] } end end 

And then you can have one line:

 name = "Henry Fillenger".match(/(?<first_name>\S+)\s+(?<last_name>\S+)/).to_hash 

I really do not recommend this, I only raise it as an interesting topic. I'm a little disappointed that MatchData no longer has a to_h or to_hash , it would make a reasonable addition to its to_a .

+2
source

All Articles