检查数组中的哈希是否存在密钥

时间:2013-09-28 18:03:47

标签: ruby arrays hash

我有一个哈希数组,例如:

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

有没有办法简单地执行此操作,还是必须嵌套每个语句?

2 个答案:

答案 0 :(得分:1)

使用一个哈希更容易:

hash = {'apple' => 10,'banana' => 5,'pear' => 1}
p hash['apple']

<强>输出
10

答案 1 :(得分:0)

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