tawheed
tawheed

Reputation: 5821

Assign hash values after being declared

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.

edit

assignment is more than 2, lets say 30+

Upvotes: 2

Views: 44

Answers (2)

Patrick Oscity
Patrick Oscity

Reputation: 54684

You could use Hash#merge! to set multiple values at once:

foo = {}

# later ...

foo.merge!({
  :baz => "mike",
  :quz => "jake"
})

Upvotes: 3

Simone Carletti
Simone Carletti

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

Related Questions