簡體   English   中英

按字符串值查找多維數組中的數組索引

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM