11

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?

7
  • Yes, it seems like this would be a better job for a real database system. Are you building a web app? Could you be using Rails? Commented Jan 18, 2013 at 17:50
  • @Eric it is to assign a rank, and get that rank based on the :id. Commented Jan 18, 2013 at 17:50
  • You're both correct, I'm leaving out much of the system for brevity, and I am using Rails. This is actually an ActiveRecord result set. Commented Jan 18, 2013 at 17:51
  • @Zenph If you are using Rails, then why not use the normal ActiveRecord query interface? I suspect there is a reasonable way to do it. Commented Jan 18, 2013 at 17:54
  • @jtbandes I would, but I've not found a reasonable way. I will have to cache these ranks, because at the minute I am fetching data from a table ordered by votes desc (which is the result set above). Essentially I will be calling Thing.find(123).rank # => 2 Commented Jan 18, 2013 at 17:57

1 Answer 1

34

You can pass a block to #index:

array.index {|h| h[:id] == 34 } # => 0
Sign up to request clarification or add additional context in comments.

2 Comments

I love answers that are straight to the point, and exactly what you need. Thanks!
This was really handy after converting an Activerecord collection to an array then wanting to still find specific records by the model hash value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.