Reputation: 5821
Lets say I declared a hash like
foo = { }
Under normal circumstance, if I need to add a new item to the hash, I would simply do
foo[:baz] = "mike"
foo[:quz] = "jake"
I was wondering whether it was possible to do the above using a block to avoid repetitive code.
assignment is more than 2, lets say 30+
Upvotes: 2
Views: 44
Reputation: 54684
You could use Hash#merge!
to set multiple values at once:
foo = {}
# later ...
foo.merge!({
:baz => "mike",
:quz => "jake"
})
Upvotes: 3
Reputation: 176412
To add a new item to an Hash (or to be precise, to assign a value to as specific hash key) you use the following syntax
hash[key] = value
There is no more succinct way to do it and there would be no advantage of using a block in this context.
If you have multiple values, you can use merge
foo.merge({
baz: "mike",
quz: "jake",
})
or
foo.merge(baz: "mike", quz: "jake")
You can also compose the Hash from a different data set, for example
values = [:baz, "mike", :quz, "jake"]
foo.merge(Hash[values])
But the best solution probably depends on how you get the values that you want to add to the Hash.
Upvotes: 0