Skip to content

Instantly share code, notes, and snippets.

@masukomi
Last active May 10, 2019 15:49
Show Gist options
  • Save masukomi/4d41c6548da83e110a5c7c85e0512153 to your computer and use it in GitHub Desktop.
Save masukomi/4d41c6548da83e110a5c7c85e0512153 to your computer and use it in GitHub Desktop.
an implementation of ruby's Flatten ... in ruby
class Array
# Performs the same function as
# flatten, only slower (because it's in Ruby
# and .flatten is implemented in C)
def slow_flatten(arr = self, result = [])
if arr.size > 0
first = arr.first
if ! arr.first.is_a? Array
result.push(first)
else
result.concat( slow_flatten(first, []) )
end
return slow_flatten(arr[1..-1], result)
else
return result
end
end
end
require "spec_helper"
require "array"
RSpec.describe Array do
context "#slow_flatten" do
it "should not blow up on empty arrays" do
expect([].slow_flatten).to(eq([]))
end
it "should flatten arrays" do
expect([[1,2,[3]],4].slow_flatten).to(eq([1,2,3,4]))
end
it "should not flatten arrays in hashes in arrays" do
expect([1, 2, [3, 4, [5, 6]], {7=>[8, [9]]}].slow_flatten).to(eq(
[1, 2, 3, 4, 5, 6, {7=>[8, [9]]}]))
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment