ruby - 根据子哈希值获取数组索引

标签 ruby

假设我有这个:

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

如何根据id获取索引?我想要做的是在搜索 id: 34 时返回 0,在搜索 id: 2< 时返回 1/。什么是最有效的方法?

最佳答案

你可以将一个 block 传递给#index:

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

关于ruby - 根据子哈希值获取数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14404618/

相关文章:

ruby-on-rails - 迪尔德 : lazy symbol binding failed: Symbol not found: _ruby_run when using heroku

ruby-on-rails - 为什么 Rails 服务器会出现 "Could not find ' railties 错误?

ruby - 将 ruby​​ 源代码从旧样式转换为新样式哈希

ruby-on-rails - Rails 记录不关联

javascript - 使用 Ruby Mechanize 更改 select 中的选项

ruby-on-rails - if语句基于表单select rails

ruby - Rails 3 + Devise - 登录用户无法打开页面更改密码

c# - 良好做法 : Loop And If statement

ruby - 脚本在命令行中成功执行但不是作为 cron 作业

javascript - 来自 Rails 的嵌入式可执行 JS