我一直在尝试将包含数字的数组收集到一个数组中。如果我尝试使用 + 它返回空数组作为输出。使用 concat 返回预期的数字数组。它是如何工作的,这些 Ruby 方法之间的主要区别是什么?
0.step.with_object([]) do |index, output|
output + [index]
break output if index == 100
do # returns empty array
0.step.with_object([]) do |index, output|
output.concat [index]
break output if index == 100
end # returns an array contains digits from 0 to 100
最佳答案
不同于Enumerable#reduce
, Enumerable#each_with_object
通过减少过程传递相同的对象。
Array#+
创建一个新实例,保持原始对象不变。
Array#concat
改变原始对象。
使用reduce
,结果是一样的:
0.step.reduce([]) do |acc, index|
break acc if index > 100
acc + [index]
end
关于arrays - Ruby + 和数组的 concat 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56592942/