Ruby: more idiomatic way of "upserting" an array value in a hash

533 views Asked by At

I have a hash of people, where each person holds an array of values.

If a person doesn't exist in the hash, I want to create a new array with a value, and add it to the hash. If they do exist, I want to find the corresponding array and add the item to it.

This code seems a bit long-winded for such a simple operation (an upsert, basically). Is there a more idiomatic way of writing this?

people = {}

person_values = people.fetch(name, [])
person_values << item
people[name] = person_values
1

There are 1 answers

0
user4987274 On BEST ANSWER

Hashes in ruby can be constructed with a codeblock that is executed when an element is first accessed. The idiomatic way in ruby to rewrite your code would be:

people = Hash.new { |hash, key| hash[key] = [] }

people[name] << item