我需要帮助......
我有这样的哈希:
@ingredients = Hash.new
@ingredients[1] = "Biscottes Mini(recondo)"
@ingredients[2] = "Abadejo"
@ingredients[3] = "Acelga"
@ingredients[4] = "Agua de Coco"
@ingredients[5] = "Ajo"
@ingredients[6] = "Almidón de Arroz"
@ingredients[7] = "Anillos Con Avena Integral cheerios (nestle)"
@ingredients[8] = "Apio"
当我写“scotte”时,我需要搜索那个哈希以找到“Biscottes Mini(recondo)”
一些帮助?
THK!
答案 0 :(得分:2)
为什么在这里使用Hash而不是数组?你似乎没有使用除整数之外的其他键。
无论如何,这个解决方案适用于数组和哈希:
search_term = 'scotte'
# you could also use find_all instead of select
search_results = @ingredients.select { |key, val| val.include?(search_term) }
puts search_results.inspect
答案 1 :(得分:1)
您可以在哈希上调用select
(或find
,如果您只想要第一个匹配项),然后传入一个块,该块评估是否在结果哈希中包含键/值。该块将键和值作为参数传递,因此您可以评估键或值是否匹配。
search_value = "scotte"
@ingredients.select { |key, value| value.include? search_value }