Ruby 矩阵类的flatten()函数
flatten()是一个数组类方法,用于返回扁平化的数组,即一维数组。
语法。Array.flatten()
参数。数组
返回一维数组
例子 #1 :
# Ruby code for flatten() method
# declaring array
a = [[18, 22],
[ 33, nil, 5, 6]]
# declaring array
b = [[[1, 4, 1, 1, 88, 9]]]
# flatten
puts "flatten : #{a.flatten()}\n\n"
# flatten
puts "flatten : #{b.flatten()}\n\n"
输出:
flatten : [18, 22, 33, nil, 5, 6]
flatten : [1, 4, 1, 1, 88, 9]
例子 #2 :
# Ruby code for flatten() method
# declaring array
a = [["abc", "nil", ],
["dog"]]
# declaring array
b = [[[["cow", nil, "dog"]]]]
# flatten
puts "flatten : #{a.flatten()}\n\n"
# flatten
puts "flatten : #{b.flatten()}\n\n"
输出:
flatten : ["abc", "nil", "dog"]
flatten : ["cow", nil, "dog"]