正如問題所問的那樣,我試圖回傳哈希值等于的索引:
PRODUCT_DISCOUNT_TIERS = [
{
product_selector_match_type: :include,
product_selector_type: :tag,
product_selectors: ["Test Custom Hats"],
tiers: "test tiers"
},
{
product_selector_match_type: :include,
product_selector_type: :tag,
product_selectors: ["Bulk Discount Hat"],
tiers: "test tiers"
},
{
product_selector_match_type: :include,
product_selector_type: :tag,
product_selectors: ["Bulk Discount Blah"],
tiers: "test tiers"
},
{
product_selector_match_type: :include,
product_selector_type: :type,
product_selectors: ["Foo Blah Hats"],
tiers: "test tiers"
},
]
在這里,我想要“Foo Blah Hats”所在的索引:我的嘗試是:
getindx = PRODUCT_DISCOUNT_TIERS.find_index { |w| w[:product_selectors] == "Foo Blah Hats"}
print getindx
uj5u.com熱心網友回復:
您的代碼不起作用,因為您的哈希存盤["Foo Blah Hats"]并且您正在搜索"Foo Blah Hats".
您可能需要檢查是否"Foo Blah Hats"包含在該陣列中:
getindx = PRODUCT_DISCOUNT_TIERS.find_index { |w|
w[:product_selectors].include? "Foo Blah Hats"
}
uj5u.com熱心網友回復:
試試這個
def find_index_of_hash_value(hash_array, value)
hash_array.each_with_index do |hash, index|
if hash.values.include?(value)
return index
end
end
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/478567.html
標籤:红宝石
上一篇:在連接給定字串中具有奇數和偶數索引的元素后,輸出在2行中給出
下一篇:在Ruby中將正數更改為負數?
