如果多维数组中包含唯一字符串,我需要数组的索引。
数组:
[
{: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/