Skip to content

Instantly share code, notes, and snippets.

@webgago
Created January 14, 2017 07:25
Show Gist options
  • Save webgago/8f4861fb8a8755ae3f51249b810cab12 to your computer and use it in GitHub Desktop.
Save webgago/8f4861fb8a8755ae3f51249b810cab12 to your computer and use it in GitHub Desktop.
class Array
# array.to_flatten -> new array
#
# Returns a new array that is a one-dimensional flattening of +self+
# (recursively).
#
# That is, for every element that is an array, extract its elements into
# the new array.
#
# a = [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
# a.to_flatten #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def to_flatten
self.inject([]) do |result, value|
if value.is_a?(Array)
result += value.to_flatten
else
result << value
end
end
end
end
require 'spec_helper'
describe Array do
describe '#to_flatten' do
subject { [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10] }
it 'returns a new array that is a one-dimensional flattening of self' do
expect(subject.to_flatten).to eql([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
end
context 'with flatten array' do
subject { [1, 2, 3] }
it 'returns a new array' do
expect(subject.to_flatten).not_to be subject
expect(subject.to_flatten).to eql subject
end
end
context 'with empty array' do
subject { [] }
it 'returns a new empty array' do
expect(subject.to_flatten).to be_empty
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment