Ruby on rails RubyonRails2哈希中的搜索字符串

Ruby on rails RubyonRails2哈希中的搜索字符串,ruby-on-rails,ruby,search,hash,Ruby On Rails,Ruby,Search,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]

我需要你的帮助

我有这样一个杂凑:

@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

请参见

您可以对哈希调用
选择
(或
查找
,如果您只需要第一个匹配),然后传入一个块,该块计算是否将键/值包括在结果哈希中。块将键和值作为参数传递,因此可以计算键或值是否匹配

search_value = "scotte"
@ingredients.select { |key, value| value.include? search_value }
key.include('scotte')->val.include('scotte'))