Get array index based on child's hash value

Say I have this:

[ { :id => 34, :votes_count => 3 }, { :id => 2, :votes_count => 0 }, ] 

How to get id based index? What I want to do is return 0 when searching for id: 34 and 1 when searching for id: 2 . What is the most effective way?

+4
source share
1 answer

You can pass the #index block:

 array.index {|h| h[:id] == 34 } # => 0 
+13
source

All Articles