2013-10-20 33 views
0

我有一个数组:搜索哈希值返回键在Ruby中

array = ["One is enough", "Two is a couple", "Where's the beef?", "One"]

然后我有一个哈希:

hash = {"one" => "Defined", 
     "two" => "Test" 
     } 

我需要遍历每个对象array和查看该对象是否包含在hash键中找到的子字符串。如果发现,它应该返回hash的值。否则,它应该返回undefined。最终的目标是创建一个数组,看起来像这样:

final_array = ["Defined,"Test","Undefined","Defined"]

我怎么能写循环有效?

回答

2

这里有一个办法:

array = ["One is enough", "Two is a couple", "Where's the beef?", "One"] 
hash = {"one" => "Defined","two" => "Test"} 

array.map{|e| hash.find(proc{["undefined"]}){|k,v| e.downcase.include? k}.last} 
# => ["Defined", "Test", "undefined", "Defined"] 

说明:

Enumerable#find将是不错的主意。正如文档所说 - 传递枚举中的每个条目以阻止。返回第一个块不是假的。 如果没有对象匹配,则调用ifnone并在指定时返回结果,否则返回nil。

我用Array#map,并将每个元素字符串传递给块。现在我在hash上拨打#find。现在hash.find将每个key/value对传递给hash.find方法块。在该块内部,我在e上调用String#include?方法,通过作为#include?方法的参数。如果#include?测试结果为true,则返回该迭代的key/value,否则将执行默认参数proc{["undefined"]}.call

希望有帮助!

+0

完美工作 - 您有任何可以解释该方法发生了什么的机会?我必须更好地使用和理解这些内衬。 – Luigi

+0

@Luigi给我一点时间.. –

+0

当然 - 感谢您的帮助。 – Luigi

0
hash = {"one" => "Defined", "two" => "Test"} 
array = ["One is enough", "Two is a couple", "Where's the beef?", "One"] 

hash.default = "Undefined" 
keys = hash.keys 
array.map {|a| hash[(a.split.map(&:downcase) & keys).first]} 
  • 如果散列不包含密钥 'K',哈希[K] => “未定义”
  • a.split.map(&:downcase)的变化,例如,一个=“一个足够“到”一个就足够了“
  • 与键的交点等于[”一“],[”二“],[零],[”一“],分别为
  • 。首先是提取来自1元素阵列的散列密钥
  • 在计算的散列密钥处计算散列,散列[ni l] =>“未定义”(默认值)