Skip to content

Instantly share code, notes, and snippets.

@qhwa
Last active October 7, 2015 15:39
Show Gist options
  • Select an option

  • Save qhwa/b19f72ca2e0bf982db4c to your computer and use it in GitHub Desktop.

Select an option

Save qhwa/b19f72ca2e0bf982db4c to your computer and use it in GitHub Desktop.
implementation of Array#flatten in ruby
# implementation of Array#flatten with ruby
def flatten arr
return arr unless arr.is_a? Array
arr.reduce([]) do |out, item|
out.push *flatten(item)
end
end
if __FILE__ == $0
# gem install minitest
# gem install minitest-reporters
require 'minitest/autorun'
require 'minitest/reporters'
describe method(:flatten) do
it "works with one level depth array" do
flatten([1]).must_equal [1]
flatten([1, 10]).must_equal [1, 10]
end
it "works with two level depth array" do
flatten([[1]]).must_equal [1]
flatten([1, [2]]).must_equal [1, 2]
flatten([[1], 2]).must_equal [1, 2]
flatten([[1], [2]]).must_equal [1, 2]
end
it "works with more level depth array" do
flatten([1, [1, [2, [3]]]]).must_equal [1, 1, 2, 3]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment