Skip to content

Instantly share code, notes, and snippets.

@texpert
Last active October 13, 2019 02:55
Show Gist options
  • Save texpert/7378c7e82d3a10691214b3347f35c632 to your computer and use it in GitHub Desktop.
Save texpert/7378c7e82d3a10691214b3347f35c632 to your computer and use it in GitHub Desktop.
Flatten Ruby implementation
# 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