Last active
October 13, 2019 02:55
-
-
Save texpert/7378c7e82d3a10691214b3347f35c632 to your computer and use it in GitHub Desktop.
Flatten Ruby implementation
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
# frozen_string_literal: true | |
def flatten(arg) | |
return "arg should be an array, but was #{arg.inspect} instead" if arg.nil? || !arg.is_a?(Array) | |
@result = [] | |
analyze(arg) | |
@result | |
end | |
def analyze(member) | |
member.each do |m| | |
m.is_a?(Array) ? analyze(m) : @result << m | |
end | |
end | |
arg = [[1, 2, [3]], 4] | |
puts flatten(arg).inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment