ruby-on-rails - 通过字符串值查找多维数组中数组的索引
问题描述
如果它包含唯一的字符串,我需要多维数组中的数组索引。
大批:
[
{: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]
,因为 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
推荐阅读
- azure - 将 Azure 监视器容器添加到仪表板
- reactjs - 在 JSX 循环中向函数传输数据:作用域函数与数据属性
- angular - 使用快速服务器和 passport.js 进行 Angular SPA 身份验证 -> 路由问题
- ruby-on-rails - Rails Form_with 显示内联错误信息
- javascript - 我使用 .catch 来捕获对承诺的拒绝,但它说我使用 .catch
- c# - DateTime 仅在 Internet Explorer 上解析确切错误
- javascript - 缩小时如何在高图中对数据进行分组
- python - Python2 错误在 MacOS 上使用 ncat 服务器错误在第 50 行 Login() SyntaxError: invalid character in identifier
- scheme - lilypond:在音乐功能中不给不可见的(优雅)音符留出空间
- python - 如何循环列表的所有内容?