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 .
source share