Ruby on Rails 2 search string in Hash

2019-08-05 09:45发布

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"

Some help?

Thk!

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-05 10:11

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

查看更多
姐就是有狂的资本
3楼-- · 2019-08-05 10:23

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.

search_value = "scotte"
@ingredients.select { |key, value| value.include? search_value }
查看更多
登录 后发表回答