简体   繁体   English

遍历哈希数组并添加到特定哈希值的值

[英]Iterate over an array of hashes and add to the value of specific hash values

If you have an array of hashes such as: 如果您有一系列哈希,例如:

t = [{'pies' => 1}, {'burgers' => 1}, {'chips' => 1}]

what would be an efficient and readable way to add 1 to the value of a hash that has a particular key such as 'pies' ? 将具有特殊键(例如'pies'的哈希值加1的有效且易读的方法是什么?

Here's one way to increment the value(s) of an array's hashes based on a desired key: 这是一种根据所需键增加数组哈希值的方法:

t = [{ 'pies' => 1 }, { 'burgers' => 1 }, { 'chips' => 1 }]

t.each { |hash| hash['pies'] += 1 if hash.key?('pies') }
# => [{"pies"=>2}, {"burgers"=>1}, {"chips"=>1}]

Hope this helps! 希望这可以帮助!

If you know there's only one hash that could take the key 'pies' then you can use find and increase the value it has, like: 如果您知道只有一个哈希可以使用键“ pies”,则可以使用find并增加其具有的值,例如:

array = [{ 'pies' => 1 }, { 'burgers' => 1 }, { 'chips' => 1 }]
pies_hash = array.find { |hash| hash['pies'] }
pies_hash['pies'] += 1
p array
# [{"pies"=>2}, {"burgers"=>1}, {"chips"=>1}]

Enumerable#find will try to find the element that satisfies the block and stops the iteration when it returns true. Enumerable#find将尝试查找满足该块的元素,并在返回true时停止迭代。

You're using the wrong data structure. 您使用了错误的数据结构。 I recommend using a Hash. 我建议使用哈希。

Each item on your menu can only have one count (or sale), that is each item is unique. 菜单上的每个项目只能具有一个计数(或销售),即每个项目都是唯一的。 This can be modelled with a hash with unique keys (the items) and their corresponding values (the counts). 可以使用具有唯一键(项目)和其对应值(计数)的哈希来建模。

t = {'pies' => 1, 'burgers' => 1, 'chips' => 1}

Then we can access keys and add to the count: 然后,我们可以访问键并添加到计数中:

t['pies'] += 1
t #=> t = {'pies' => 2, 'burgers' => 1, 'chips' => 1}

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

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