通过字符串值在多维数组中查找数组的索引

时间:2019-07-10 16:26:17

标签: 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'}

1 个答案:

答案 0 :(得分:3)

这将返回nil,因为数组中没有值i(也不是#FFF600)的元素FFF600(索引),因此您需要访问{{ 1}}键值:

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
相关问题