首页 > 解决方案 > 通过字符串值查找多维数组中数组的索引

问题描述

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

大批:

[
    {: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'}

标签: ruby-on-railsruby

解决方案


这是返回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],因为 using 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

推荐阅读