0

我有一个数组:

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"]

如何有效地编写该循环?

4

2 回答 2

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,并将每个元素字符串传递给块。现在在我打电话的街#find区内hash。现在hash.find将每一key/value对传递给hash.find方法块。在该块内,我正在调用String#include?方法e,将作为参数传递给该#include?方法。如果#include?测试结果true,则key/value返回该迭代的,否则proc{["undefined"]}.call正在执行默认参数。

希望有帮助!

于 2013-10-20T17:17:27.560 回答
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]}
  • 如果 hash 不包含键 'k',hash[k] => "Undefined"
  • a.split.map(&:downcase) 改变,例如 a = "One is Enough" 到 "one is enough"
  • 与键的交集分别等于 ["one"], ["two"], [nil], ["one"]
  • .first 是从一元数组中提取哈希键
  • 散列在计算的散列键处进行评估, hash[nil] => "Undefined" (默认)
于 2013-10-20T20:10:39.037 回答