Last active
December 11, 2018 13:47
-
-
Save taras2358/2c6a0bcbc8995ba4349f80415774a0e7 to your computer and use it in GitHub Desktop.
Mixin for extending ruby array with :recursive_flatten method (as supposedly it should be used often). Used default tests (instead of rspec) for simplicity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
class Array | |
module Mixins | |
# Mixing for providing flatten method into Array | |
module Flatten | |
# Returns a flatten copy of array | |
# Example: [[1,2,[3]],4].recursive_flatten => [1, 2, 3, 4] | |
def recursive_flatten(result: []) | |
each do |element| | |
if element.is_a?(Array) | |
element.recursive_flatten(result: result) | |
else | |
result << element | |
end | |
end | |
result | |
end | |
end | |
end | |
end | |
Array.include Array::Mixins::Flatten |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'test/unit' | |
require_relative './array_flatten' | |
class TestArrayFlattenMixin < Test::Unit::TestCase | |
def test_empty_array | |
subject = [].recursive_flatten | |
assert_equal(subject, []) | |
end | |
def test_simple_array | |
subject = [2, 3, 4, 5].recursive_flatten | |
assert_equal(subject, [2, 3, 4, 5]) | |
end | |
def test_array | |
subject = [[1, 2, [3]], 4].recursive_flatten | |
assert_equal(subject, [1, 2, 3, 4]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment