Skip to content

Instantly share code, notes, and snippets.

@grvm
Last active August 21, 2016 12:50
Show Gist options
  • Save grvm/f00b7e7e0f46bffa920f8326f417893a to your computer and use it in GitHub Desktop.
Save grvm/f00b7e7e0f46bffa920f8326f417893a to your computer and use it in GitHub Desktop.
Ruby custom implementation of Array#flatten using Regular Expressions
x = [[1], [2, 3, [4, 5, 6, [7, 8, 9, 10], 11], 12, 13], 14, 15, 16]
class Array
def flattener
matches = self.to_s.scan(/\d+/)
matches.collect(&:to_i)
end
end
puts "Specs"
puts "====="
cases = [
[],
[1, [2]],
[1, [2, [3]]],
[1, [[2, 3], 4], 5],
[1, [2, [3, 4]], 5, [6,[7]]],
[1, [2, [3, 4], [5, 6, [7, 8, [9, 10, 11], [12]]]], 13, [14, 15], [16]]
]
cases.each_with_index do |the_case, i|
p "#{i}. #{the_case}"
ruby_one = the_case.flatten
custom_one = the_case.flattener
p "ruby_one: #{ruby_one}"
p "custom_one: #{custom_one}"
puts (ruby_one == custom_one) ? "pass" : "fail"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment