`inject` 不在累加器中添加空白 space
`inject` does not add the blank space in accumulator
在此代码中:
b = ["here", "are", "things"]
b.inject { |str, v| str+="#{v} " }
# => "hereare things "
return 值不应该是 "here are things"
吗?我假设它将第一个值传递给累加器 str
。有没有办法return"here are things "
?
I'd assume it's passing in the first value to the accumulator
正确,因为未定义初始值,您集合的第一个元素成为初始值。使固定?提供初始值:
b = ['here', 'are', 'things']
b.inject('') { |memo, elem| memo + "#{elem} " } # => "here are things "
在单词前加上space,像这样。 结果中没有尾随 space。
["here", "are", "things"].inject { |str, v| str+=" #{v}" }
#=> "here are things"
你也可以像下面这样做,但仍然没有尾随 space
['here', 'are', 'things'].inject { |m, e| "#{m} #{e}" }
#=> "here are things"
在此代码中:
b = ["here", "are", "things"]
b.inject { |str, v| str+="#{v} " }
# => "hereare things "
return 值不应该是 "here are things"
吗?我假设它将第一个值传递给累加器 str
。有没有办法return"here are things "
?
I'd assume it's passing in the first value to the accumulator
正确,因为未定义初始值,您集合的第一个元素成为初始值。使固定?提供初始值:
b = ['here', 'are', 'things']
b.inject('') { |memo, elem| memo + "#{elem} " } # => "here are things "
在单词前加上space,像这样。 结果中没有尾随 space。
["here", "are", "things"].inject { |str, v| str+=" #{v}" }
#=> "here are things"
你也可以像下面这样做,但仍然没有尾随 space
['here', 'are', 'things'].inject { |m, e| "#{m} #{e}" }
#=> "here are things"