Hash.each 和 Hash.inject 实现的不同结果

Different results from Hash.each and Hash.inject implementations

我试图理解为什么我从两个我认为功能相同的表达式中得到不同的结果。

each方法:

matches = {}
@entries.each do|entry, definition|
    matches.merge!({entry => definition}) if entry.match(/^#{entry_to_find}/)
end
matches

inject方法:

@entries.inject({}) {|matches, (entry, definition)| matches.merge!
({entry => definition}) if entry.match(/^#{entry_to_find}/)}

each 代码块在 运行 时给出正确答案,但 inject 一直返回 nil,我不明白为什么。我希望使用注入,因为它是一段更短的代码。

因为if会在条件不满足的情况下returnnil,在下一次迭代中会作为matches的值.使用 Enumerable#each_with_object 代替:

@entries.each_with_object({}) do |(entry, definition), matches| 
  matches.merge!({entry => definition}) if entry.match(/^#{entry_to_find}/)
end

我觉得 is correct. As for shorter alternatives, as you want those unmodified key-value pairs of @entries that fulfill your condition, have you considered Hash#select?

matches = @entries.select { |entry, definition| entry.match(/^#{entry_to_find}/) }