Ruby on Rails 2在哈希中搜索字符串 [英] Ruby on Rails 2 search string in Hash

查看:144
本文介绍了Ruby on Rails 2在哈希中搜索字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要这方面的帮助......



我有这样的散列:

  @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ónde Arroz
@ ingredients [7] =Anillos Con Avena Integral cheerios(nestle)
@ingredients [8] =Apio

当我编写scotte时,为了找到Biscottes Mini(recondo),我需要搜索那个哈希。

一些帮助?



Thk!

解决方案

哈希在这里,而不是一个数组?您不会使用除整数以外的其他键。



无论如何,此解决方案适用于Array和Hashes:

  search_term ='scotte'
#您也可以使用find_all而不是选择
search_results = @ ingredients.select {| key,val | val.include?(search_term)}
puts search_results.inspect

请参阅 http://ruby-doc.org/core/classes/Enumerable.html#M001488

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!

解决方案

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

这篇关于Ruby on Rails 2在哈希中搜索字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆