简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM