Array#flatten
with depth argument is useful.
[[1], [2], [[3], 4]].flatten(1)
#=> [1, 2, [3], 4]
That's been available since ruby 1.8.7, but older ruby such as ruby 1.8.6 doesn't support it.
Here is the pure-ruby implementation of Array#flatten
. Use it in case.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
#!/opt/local/bin/ruby for 1.8.7 | |
#!ruby191 | |
#!ruby192 | |
if RUBY_VERSION <= '1.8.6' | |
class Array | |
alias orig_flatten flatten | |
def flatten(depth = -1) | |
if depth < 0 | |
orig_flatten | |
elsif depth == 0 | |
self | |
else | |
inject([]) {|m, i| | |
Array === i ? m + i : m << i | |
}.flatten(depth - 1) | |
end | |
end | |
end | |
end | |
p RUBY_VERSION | |
p [1, 2, 3].flatten == [1, 2, 3] | |
p [1, 2, [3]].flatten == [1, 2, 3] | |
p [[1], [2], [3, 4]].flatten == [1, 2, 3, 4] | |
p [[1], [2], [[3], 4]].flatten == [1, 2, 3, 4] | |
p [1, 2, 3].flatten(1) == [1, 2, 3] | |
p [1, 2, [3]].flatten(1) == [1, 2, 3] | |
p [[1], [2], [3, 4]].flatten(1) == [1, 2, 3, 4] | |
p [[1], [2], [[3], 4]].flatten(1) == [1, 2, [3], 4] | |
p [[1, 2], [[[3], 4]]].flatten(1) == [1, 2, [[3], 4]] | |
p [[1], [2], [[3], 4]].flatten(2) == [1, 2, 3, 4] | |
p [[1, 2], [[[3], 4]]].flatten(2) == [1, 2, [3], 4] | |
p [[1, 2], [[[3], 4]]].flatten(3) == [1, 2, 3, 4] | |
p [[1, 2], [[[3], 4]]].flatten(-1) == [1, 2, 3, 4] | |
p [[1, 2], [[[3], 4]]].flatten(0) == [[1, 2], [[[3], 4]]] |
I used it for my library spawn-for-legacy
to support ruby 1.8.6.
Rails programmers don't need this code. Rails now only supports ruby newer than 1.8.7.
No comments:
Post a Comment