Skip to content

Instantly share code, notes, and snippets.

@poshboytl
Created February 23, 2016 09:57
Show Gist options
  • Save poshboytl/3622d361db3dcc46dcf1 to your computer and use it in GitHub Desktop.
Save poshboytl/3622d361db3dcc46dcf1 to your computer and use it in GitHub Desktop.
Implement the ruby's flatten method.
# 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
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