例如,我有一个哈希数组:
array = [{apple => 10},{banana => 5},{pear => 1}]
我想做类似以下的事情(部分伪代码)
fruit = "Orange"
if array.anyhash.key = fruit do |fruit|
array << {fruit => 1}
else
array.hashwithkey(fruit).value += 1
end
有没有办法简单地做到这一点,还是我必须嵌套每个语句?
使用一个哈希更容易:
hash = {'apple' => 10,'banana' => 5,'pear' => 1}
p hash['apple']
输出:
10
a = [{'apple' => 10},{'banana' => 5},{'pear' => 1}]
fruit = 'orange'
match = a.find {|h| h.member? fruit }
if match
match[fruit] += 1
else
a << {fruit: 1}
end
最好使用简单的哈希。
a = {'apple' => 10, 'banana' => 5, 'pear' => 1}
fruit = 'orange'
a[fruit] = a.fetch(fruit, 0) + 1