1

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?

3
  • 1
    Yes, use one Hash instead of array of hashes ;) Commented Sep 28, 2013 at 18:06
  • Is there any reason to have an array of hashes instead of a single hash? Commented Sep 28, 2013 at 18:06
  • It is not clear what you mean by your pseudocode. Commented Sep 28, 2013 at 18:34

2 Answers 2

1

It's easier to use one hash:

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

OUTPUT:
10

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I feel a bit stupid. Shows what happens when I don't write code for a couple of months.
With hash defined as above, I think OP was looking for if hash.has_key('apple')... @lpsum: since hash['apple'] => nil if 'apple' is not a key, you could use if(hash['apple'])... but that's a problem in situations where the hash may contain, say, :a=>nil, in which case hash[:a] => nil.
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 

It's better to use simple hash.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.