Home > OS >  return the index where the hash value is equal to
return the index where the hash value is equal to

Time:05-17

As the question asks I'm attempting to return the index where the value of the hash is equal to:

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"
  },
]

Here I want the index where "Foo Blah Hats" is: My attempt is:

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

print getindx

CodePudding user response:

Your code doesn't work because your hash stores ["Foo Blah Hats"] and you're searching for "Foo Blah Hats".

You may want to check if "Foo Blah Hats" is included in that array:

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

CodePudding user response:

Try this one

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
  •  Tags:  
  • ruby
  • Related