Notaion: Hash[*array_variable.flatten]

Can someone explain what the “*” operator inside the hash is doing here
what that notation is referred to in this context ? thanks

irb(main):006:0* mail_config
=> {“server_setings”=>{“address”=>“”, “port”=>25}}

irb(main):019:0> Hash[*mail_config[‘server_setings’].map { |k, v|
[k.to_sym, v.t

o_s] }.flatten]

=> {:address=>“”, :port=>“25”}

Try …

def test(arg1, arg2=nil, arg3=nil, arg4=nil)
p arg1
p arg2
p arg3
p arg4

Without the splat

test(mail_config[‘server_setings’].map { |k, v| [k.to_sym, v.to_s]

[:address, “”, :port, “25”]




With the splat

test(*mail_config[‘server_setings’].map { |k, v| [k.to_sym, v.to_s]




So, the splat operator explodes an array into the arguments of the
First case without the splat you can see that the whole Array goes
into the arg1.
Second, with the splat, each arg gets one of the Array elements.

At your context the splat makes the call to Hash[] compatible with the
Hash[key1, value1, key2, value2, key3, value3, …]

One thing to note is:
Hash[*mail_config[‘server_setings’].map { |k, v| [k.to_sym, v.to_s]
Hash[mail_config[‘server_setings’].map { |k, v| [k.to_sym, v.to_s] }]

Without the splat and without flatten are equivalents (for the given


And you can do it differently in a way that I think is more

intuitive (for my taste).

mail_config[‘server_setings’].each_with_object({}) { |(k, v), hsh|
hsh[k.to_sym] = v.to_s }

What do you think?

Hope it helped you,
Abinoam Jr.

On Fri, Sep 27, 2013 at 4:05 PM, [email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs