ruby-on-rails - 通过字符串值查找多维数组中数组的索引

标签 ruby-on-rails ruby

如果多维数组中包含唯一字符串,我需要数组的索引。

数组:

[
    {:id=>5, :name=>"Leaf Green", :hex_value=>"047115"},
    {:id=>15, :name=>"Lemon Yellow", :hex_value=>"FFF600"},
    {:id=>16, :name=>"Navy", :hex_value=>"285974"}
]

如果 'FFF600' 的 hex_value 存在,则返回数组位置,在本例中为 1。

这是我所在的位置,但它正在返回 []。

index = array.each_index.select{|i| array[i] == '#FFF600'}

最佳答案

这将返回 nil,因为数组中没有值为 #FFF600 的元素 i(索引)(FFF600),需要访问hex_value键值:

p [
  {:id=>5, :name=>"Leaf Green", :hex_value=>"047115"},
  {:id=>15, :name=>"Lemon Yellow", :hex_value=>"FFF600"},
  {:id=>16, :name=>"Navy", :hex_value=>"285974"}
].yield_self { |this| this.each_index.select { |index| this[index][:hex_value] == 'FFF600' } }
# [1]

给你 [1],因为使用了 select,如果你只想第一次出现,你可以使用 find

我在那里使用 yield_self,以避免将数组分配给变量。这相当于:

array = [
  {:id=>5, :name=>"Leaf Green", :hex_value=>"047115"},
  {:id=>15, :name=>"Lemon Yellow", :hex_value=>"FFF600"},
  {:id=>16, :name=>"Navy", :hex_value=>"285974"}
]
p array.each_index.select { |index| array[index][:hex_value] == 'FFF600' }
# [1]

作为 Ruby,您可以使用以下方法:Enumerable#find_index

p [
  {:id=>5, :name=>"Leaf Green", :hex_value=>"047115"},
  {:id=>15, :name=>"Lemon Yellow", :hex_value=>"FFF600"},
  {:id=>16, :name=>"Navy", :hex_value=>"285974"}
].find_index { |hash| hash[:hex_value] == 'FFF600' }
# 1

关于ruby-on-rails - 通过字符串值查找多维数组中数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56974969/

相关文章:

ruby - 如果 'key' 或 'value' 包含 ruby​​ 中的值,则选择哈希元素

ruby-on-rails - DateTime 类的意义何在?

ruby-on-rails - Rake 测试失败 assert_match

ruby-on-rails - 如何在不改变相同值 ruby 位置的情况下按降序对哈希进行排序

ruby-on-rails - Rails 3使用自定义消息验证许多列的存在

ruby-on-rails - 合并参数 rails

ruby - 有什么方法可以自动 `puts` Ruby 脚本中的最后一个表达式?

ruby - 无||假与假|| ruby 中没有

ruby-on-rails - Ruby on Rails - has_many 基于 "kind"

ruby-on-rails - rails 。 Capybara fill_in 找到文本输入但没有 fill_in