arraysrubyconcatenationstep

What the difference between Ruby + and concat for arrays?


I've been trying to collect arrays with digits into one array. If I try to use + it returns emty array as output. Using concat returns expected array of digits. How does it work and what the main difference between these Ruby methods?

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

Solution

  • Unlike Enumerable#reduce, Enumerable#each_with_object passes the same object through reducing process.

    Array#+ creates a new instance, leaving the original object unrouched.
    Array#concat mutates the original object.

    With reduce the result will be the same:

    0.step.reduce([]) do |acc, index|
      break acc if index > 100
      acc + [index]
    end