注入多个块参数

时间:2011-10-18 19:59:10

标签: ruby

Solr的Sunspot gem有一个方法需要一个包含2个元素的块:

search.each_hit_with_result do |hit,result|

我正在使用它来构建一个新的结果哈希:

results = Hash.new

search.each_hit_with_result do |hit,result|
  results[result.category.title] = hit.score
end

这很酷,除了我不禁想到有一种更“红宝石”的做法,我一直在寻找令人敬畏的inject方法。我认为类似下面的内容应该是可能的,但我无法在语法上工作。有人有任何想法吗?

search.each_hit_with_result.inject({})
{|newhash,|hit,result||newhash[result.category.title]=hit.score}

2 个答案:

答案 0 :(得分:2)

我相信这个方法看起来像你想要的那样:

search.each_hit_with_result.inject({}) { |new_hash, current| new_hash[current[0]] = current[1]; new_hash }

希望对你有所帮助。

答案 1 :(得分:1)

Object#enum_for正是为此而设计的:

hit_results = search.enum_for(:each_hit_with_result)
results = Hash[hit_results.map { |hit, res| [res.category.title, hit.score] }]

在我看来,代码不应该暴露each_xyz方法,它们会促进臭臭的命令式代码(正如您正确检测到的那样)。当没有enumerators且你需要懒惰地返回数据时,这种方法是可以理解的,但现在它应该被认为是反模式。他们应该返回一个枚举或枚举器,让用户决定如何使用它。