Ruby on Rails 2在Hash中搜索字符串

我需要帮助…

我有这样的哈希:

@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!

为什么在这里使用哈希而不是数组? 您似乎不使用除整数之外的其他键。

无论如何,这个解决方案适用于数组和哈希:

 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 

见http://ruby-doc.org/core/classes/Enumerable.html#M001488

您可以在散列上调用select (或find是否只需要第一个匹配项),然后传入一个块,该块用于计算是否在结果散列中包含键/值。 该块将键和值作为参数传递,因此您可以评估键或值是否匹配。

 search_value = "scotte" @ingredients.select { |key, value| value.include? search_value }