将2d数组转换为1d(Ruby)

时间:2016-03-24 04:01:59

标签: arrays ruby

下面的代码将#startyear的副本推送到#new。我需要把它转换成1个单个数组,任何想法? 论坛没有多少

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}"

2 个答案:

答案 0 :(得分:7)

您可以使用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"]

答案 1 :(得分:2)

Array#flatten是在这里使用的明显方法,但正如Ruby的情况一样,有其他选择。这是两个。

使用Enumerable#flat_mapObject#itself

startyear.flat_map(&:itself)
  #=> ["a", "b", "z", "c", "d", "e", "f", "g", "h", "i", "j"]
在Ruby v2.2中引入了

itself。对于早期版本,请使用:

startyear.flat_map { |a| a }

使用Enumerable#reduce(又名inject

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