Posted at

Ruby Array#flattenは階層を指定できる

More than 3 years have passed since last update.

[[[]]].flatten

# => []

[[[]]].flatten(0)
# => [[[]]]
[[[]]].flatten(1)
# => [[]]
[[[]]].flatten(2)
# => []
[[[]]].flatten(-1)
# => []

デフォルト値は-1.

ネストが深くなると実害ありそうなので意識する必要がある.

[[1,[2,3]], [4,[5,6]], [7,[8,9]]].flatten

# => [1, 2, 3, 4, 5, 6, 7, 8, 9]
[[1,[2,3]], [4,[5,6]], [7,[8,9]]].flatten(1)
# => [1, [2, 3], 4, [5, 6], 7, [8, 9]]


References