return哈希值等于的索引

return the index where the hash value is equal to

正如问题所问,我正在尝试 return 哈希值等于的索引:

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

试试这个

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

您的代码无效,因为您的哈希存储 ["Foo Blah Hats"] 而您正在搜索 "Foo Blah Hats".

您可能需要检查 "Foo Blah Hats" 是否 包含在该数组中

getindx = PRODUCT_DISCOUNT_TIERS.find_index { |w| 
  w[:product_selectors].include? "Foo Blah Hats"
}