GLaDOS
GLaDOS

Reputation: 672

Is there a less awkward way to store a value in a Ruby hash?

I have a hash of hashes in Ruby to which I'm inserting new hashes or adding values to existing hashes. I keep feeling like Ruby has a better way to do this:

map   # => { 1 => {:type => "humbug", :name => "grinch" }, 2 => {:type => 2 } }

  if map[key]
    map[key].store(:name, value)
  else
    map[key] = { name: value }
  end

I want to be able to do something like

map[key].store(:name, value) || map[key] = {name: value}

but of course that fails if there is no value at map[key] ... suggestions?

Upvotes: 2

Views: 137

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230366

Is there a less awkward way?

Yes.

map[key] ||= {}
map[key].store(:name, value) # or map[key][:name] = value

Or make use of one of Hash missing value handlers.

map = Hash.new { |hash, key| hash[key] = {} }
# then set fearlessly, missing hashes will be auto-created.
map[key][:name] = value

Upvotes: 5

Related Questions