简体   繁体   English

Ruby:在哈希中“upserting”数组值的更惯用的方式

[英]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). 对于这样一个简单的操作(基本上是upsert),这段代码看起来有点啰嗦。 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. 可以使用在首次访问元素时执行的代码块来构造ruby中的哈希。 The idiomatic way in ruby to rewrite your code would be: ruby中重写代码的惯用方法是:

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

people[name] << item

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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