Last active
October 7, 2015 15:39
-
-
Save qhwa/b19f72ca2e0bf982db4c to your computer and use it in GitHub Desktop.
implementation of Array#flatten in ruby
This file contains hidden or 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
| # 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