Solr的Sunspot gem有一个方法,需要一个包含2个元素的块:
search.each_hit_with_result do |hit,result|
Run Code Online (Sandbox Code Playgroud)
我正在使用它来构建一个新的结果哈希,如下所示:
results = Hash.new
search.each_hit_with_result do |hit,result|
results[result.category.title] = hit.score
end
Run Code Online (Sandbox Code Playgroud)
这很酷,除了我不禁想到有一种更"红宝石"的做法,我一直在寻找这个很棒的inject方法.我认为类似下面的内容应该是可能的,但我无法在语法上工作.有人有任何想法吗?
search.each_hit_with_result.inject({})
{|newhash,|hit,result||newhash[result.category.title]=hit.score}
Run Code Online (Sandbox Code Playgroud)
Object#enum_for正是为此而设计的:
hit_results = search.enum_for(:each_hit_with_result)
results = Hash[hit_results.map { |hit, res| [res.category.title, hit.score] }]
Run Code Online (Sandbox Code Playgroud)
在我看来,代码永远不应该公开each_xyz方法,它们会促进有味道的命令式代码(正如您正确检测到的那样)。当没有枚举器并且您需要延迟返回数据时,这种方法是可以理解的,但现在它应该被视为一种反模式。他们应该返回一个可枚举或枚举器,并让用户决定如何使用它。