Ipsum
Ipsum

Reputation: 45

Check if key exists in hash in array

I have an array of hashes for instance:

array = [{apple => 10},{banana => 5},{pear => 1}]

I want to do something like the following (partly pseudocode)

fruit = "Orange"
if array.anyhash.key = fruit do |fruit|
    array << {fruit => 1}
else
   array.hashwithkey(fruit).value += 1
end

Is there a way to do this simply or do I have to do nested each statements?

Upvotes: 1

Views: 3509

Answers (2)

falsetru
falsetru

Reputation: 369494

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

It's better to use simple hash.

a = {'apple' => 10, 'banana' => 5, 'pear' => 1}
fruit = 'orange'
a[fruit] = a.fetch(fruit, 0) + 1

Upvotes: 0

Nir Alfasi
Nir Alfasi

Reputation: 53565

It's easier to use one hash:

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

OUTPUT:
10

Upvotes: 1

Related Questions