Created
February 23, 2016 09:57
-
-
Save poshboytl/3622d361db3dcc46dcf1 to your computer and use it in GitHub Desktop.
Implement the ruby's flatten method.
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
# In Ruby we can easily use flatten method: [[1,2,[3]],4].flatten #=> [1,2,3,4] to do this work. | |
# I guess it requires me to implement it myself. | |
module Enumerable | |
def my_flatten | |
Enumerator.new do |yielder| | |
each do |ele| | |
if ele.is_a?(Enumerable) | |
ele.my_flatten.each do |sub| | |
yielder.yield(sub) | |
end | |
else | |
yielder.yield(ele) | |
end | |
end | |
end | |
end | |
end |
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
require 'minitest/autorun' | |
require_relative 'flatten' | |
module Enumerable | |
describe "#my_flatten" do | |
before do | |
@nested_arrays = [[1, 2, [3]], 4] | |
end | |
it "should flatten the nested arrays" do | |
@nested_arrays.flatten.must_equal [1, 2, 3, 4] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment