[英]Find index of array in multidimensional array by string value
如果它包含一个唯一的字符串,我需要一个多维数组中的数组的索引。
数组:
[
{: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
,因为数组中没有元素i
(索引),值为#FFF600
(也不是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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.