Blogged by Ujihisa. Standard methods of programming and thoughts including Clojure, Vim, LLVM, Haskell, Ruby and Mathematics written by a Japanese programmer. github/ujihisa

Thursday, March 11, 2010

Compatible Array#flatten

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.

#!/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]]]
view raw gistfile1.txt hosted with ❤ by GitHub

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

Followers