Skip to content

Instantly share code, notes, and snippets.

@tlands
Last active December 19, 2015 18:09
Show Gist options
  • Save tlands/5996780 to your computer and use it in GitHub Desktop.
Save tlands/5996780 to your computer and use it in GitHub Desktop.
Recursively flatten an array. First uses Array#each, second uses no iteration. Both only use one arg. (First attempt I posted actually called my first method... so it was undoubtedly incorrect as far as no iteration goes. This one's right though.)
# recursive but with Array#each
def flatten(array)
return [array] unless array.is_a?(Array)
result = []
array.each do |x|
result += flatten(x)
end
result
end
flatten ["bananas", [1,2,3], ["apple", "cheese", [100, 20]], [true], [4.0, 7, 32]] # => ["bananas", 1, 2, 3, "apple", "cheese", 100, 20, true, 4.0, 7, 32]
flatten ["Washed Out", "Nujabes",[34,[54,67,87],67],["Pliney","Lagunitas"],[false],[23,1990,5]] # => ["Washed Out", "Nujabes", 34, 54, 67, 87, 67, "Pliney", "Lagunitas", false, 23, 1990, 5]
# 1. No iteration inside the method (inject, each, map, etc. not allowed)
# 2. No other arguments besides the input array
def flatten_recur(array)
return array if array == []
return [array] unless array.is_a?(Array)
flatten_recur(array.shift) + flatten_recur(array)
end
flatten_recur ["Washed Out", "Nujabes",[34,[54,67,87],67],["Pliney","Lagunitas"],[false],[23,1990,5]] # => ["Washed Out", "Nujabes", 34, 54, 67, 87, 67, "Pliney", "Lagunitas", false, 23, 1990, 5]
flatten_recur ["bananas", [1,2,3], ["apple", "cheese", [100, 20]], [true], [4.0, 7, 32]] # => ["bananas", 1, 2, 3, "apple", "cheese", 100, 20, true, 4.0, 7, 32]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment