I need help with this...
我需要帮助...
I have a hash like this:
我有这样的哈希:
@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"
I need to search into that hash in order to find "Biscottes Mini(recondo)" when I write "scotte"
当我写“scotte”时,我需要搜索那个哈希以找到“Biscottes Mini(recondo)”
Some help?
Thk!
2 个解决方案
#1
2
Why do you use a Hash here and not an Array? You do not seem to use other keys than integers.
为什么在这里使用哈希而不是数组?您似乎不使用除整数之外的其他键。
Anyway, this solution works for both Array and Hashes:
无论如何,这个解决方案适用于数组和哈希:
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
See http://ruby-doc.org/core/classes/Enumerable.html#M001488
#2
1
You can call select
(or find
if you only want the first match) on a hash and then pass in a block that evaluates whether to include the key/value in the result hash. The block passes the key and value as arguments, so you can evaluate whether either the key or value matches.
您可以在散列上调用select(或查找是否只需要第一个匹配项),然后传入一个块,该块用于计算是否在结果散列中包含键/值。该块将键和值作为参数传递,因此您可以评估键或值是否匹配。
search_value = "scotte"
@ingredients.select { |key, value| value.include? search_value }
#1
2
Why do you use a Hash here and not an Array? You do not seem to use other keys than integers.
为什么在这里使用哈希而不是数组?您似乎不使用除整数之外的其他键。
Anyway, this solution works for both Array and Hashes:
无论如何,这个解决方案适用于数组和哈希:
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
See http://ruby-doc.org/core/classes/Enumerable.html#M001488
#2
1
You can call select
(or find
if you only want the first match) on a hash and then pass in a block that evaluates whether to include the key/value in the result hash. The block passes the key and value as arguments, so you can evaluate whether either the key or value matches.
您可以在散列上调用select(或查找是否只需要第一个匹配项),然后传入一个块,该块用于计算是否在结果散列中包含键/值。该块将键和值作为参数传递,因此您可以评估键或值是否匹配。
search_value = "scotte"
@ingredients.select { |key, value| value.include? search_value }