Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array index based on child hash value

Tags:

ruby

Say I have this:

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

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

like image 903
Damien Roche Avatar asked Jan 18 '13 17:01

Damien Roche


1 Answers

You can pass a block to #index:

array.index {|h| h[:id] == 34 } # => 0
like image 106
jtbandes Avatar answered Sep 28 '22 16:09

jtbandes