Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 2d array into 1d (Ruby)

Tags:

arrays

ruby

The code below currently pushes a copy of #startyear into #new. I need to convert this into 1 single array, any ideas? Forums didn't have much

startyear = [["a", "b", "z"], ["c", "d"], ["e", "f"], ["g", "h", "i", "j"]]
new = []
startyear.each do |n| #.transpose here?
    puts "looping #{n}"
    new.push(n)
    #n.join is needed somewhere
    puts "#{startyear.length} is the length of startyear"
    break if startyear.length == startyear.length[4]
end
puts "your new array is : #{new}"
like image 499
whatabout11 Avatar asked Aug 11 '26 17:08

whatabout11


2 Answers

You can use Array#flatten:

startyear = [["a", "b", "z"], ["c", "d"], ["e", "f"], ["g", "h", "i", "j"]]
flattened = startyear.flatten
# flattened is now ["a", "b", "z", "c", "d", "e", "f", "g", "h", "i", "j"]
like image 151
max pleaner Avatar answered Aug 13 '26 07:08

max pleaner


Array#flatten is the obvious method to use here, but as is generally the case with Ruby, there are alternatives. Here are two.

Use Enumerable#flat_map and Object#itself

startyear.flat_map(&:itself)
  #=> ["a", "b", "z", "c", "d", "e", "f", "g", "h", "i", "j"]

itself was introduced in Ruby v2.2. For earlier versions, use:

startyear.flat_map { |a| a }

Use Enumerable#reduce (aka inject)

startyear.reduce(:+)
  #=> ["a", "b", "z", "c", "d", "e", "f", "g", "h", "i", "j"] 
like image 42
Cary Swoveland Avatar answered Aug 13 '26 07:08

Cary Swoveland