获取基于子哈希值的数组索引

Dam*_*che 5 ruby

说我有这个:

[
  {
             :id => 34,
    :votes_count => 3
  },
  {
             :id => 2,
    :votes_count => 0
  },
]
Run Code Online (Sandbox Code Playgroud)

我如何获得基于的索引id?我想要做的是0当我搜索时id: 34,以及1当我搜索时返回id: 2.什么是最有效的方式?

jtb*_*des 19

您可以将块传递给#index:

array.index {|h| h[:id] == 34 } # => 0
Run Code Online (Sandbox Code Playgroud)