OneBite.Dev - Coding blog in a bite size

merge multiple array in Ruby

Code snippet on how to merge multiple array in Ruby

def merged_array(*arrays)
  merged_array = []
  arrays.each do |array|
    array.each do |element|
      merged_array << element
    end
  end
  merged_array
end

This code takes in any number of arrays as parameters and merges them into a single array. To do this, the ‘merged_array’ is first initialized as an empty array. The ‘each’ loop then iterates through each array in the ‘arrays’ parameter, and for each of these arrays, the ‘each’ loop again iterates through each element in the array. This element is then added to the ‘merged_array’ through the assignment operator (‘<<’). Finally the ‘merged_array’ is returned, which contains all elements from each of the passed arrays in the order of their occurrence.

ruby