簡體   English   中英

注入多個塊參數

[英]Inject with multiple block parameters

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}

我相信這個方法看起來像你想要的:

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

希望對你有所幫助。

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方法,它們會促進臭臭的命令式代碼(正如您正確檢測到的那樣)。 當沒有調查員並且你需要懶惰地返回數據時,這種方法是可以理解的,但現在它應該被認為是反模式。 他們應該返回一個枚舉或枚舉器,讓用戶決定如何使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM