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?
如何根据id获取索引?我想要做的是当我搜索id:34时返回0,当我搜索id时返回1:2。最有效的方法是什么?
1 个解决方案
#1
13
You can pass a block to #index
:
您可以将块传递给#index:
array.index {|h| h[:id] == 34 } # => 0
#1
13
You can pass a block to #index
:
您可以将块传递给#index:
array.index {|h| h[:id] == 34 } # => 0