arrays - Ruby + 和数组的 concat 有什么区别?

标签 arrays ruby concatenation step

我一直在尝试将包含数字的数组收集到一个数组中。如果我尝试使用 + 它返回空数组作为输出。使用 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/

相关文章:

c - 当数组长度未知时,如何用用户输入值填充 C 中的数组

ruby-on-rails - Ruby stripe api 不触发事件

performance - GWT 字符串连接运算符 + 与 stringbuffer

php - 在 MySQL 中将一行的列连接为单个输出

javascript - 在从 PHP 数组填充的 JQuery HTML 选择列表上设置 SELECTED 属性

javascript - 匹配字谜并推送到数组

java - 在另一个类中使用类作为数组

ruby-on-rails - 如何使用 ActiveRecord 映射多个属性?

ruby - 将所有偶数索引整数乘以二

c++ - 了解 C++ 字符串连接