1

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

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

有没有办法简单地做到这一点,还是我必须嵌套每个语句?

4

2 回答 2

1

使用一个哈希更容易:

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

输出
10

于 2013-09-28T18:08:04.803 回答
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
于 2013-09-28T18:08:22.613 回答