Created
November 10, 2016 21:26
-
-
Save rubyrider/879c5bcd24b7b57e642f4d58da52fd2e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# Module MixArrayFlattener | |
# Add #flatten_array to Array for the purpose | |
# of flatten nested array | |
module MixArrayFlattener | |
InvalidArrayItemFound = Class.new(StandardError) | |
# Flatten nested array! | |
# | |
# @return single flat array, | |
# => Example: converts [1,2,[5,1],3] to [1,2,5,1,3] | |
def flatten_array | |
return self if empty? # if array is an empty array | |
# Chwck if there is at least one nested array | |
if self.select { |item| item.is_a?(Array) }.nil? | |
return self | |
end | |
# iniatializing output array variable! | |
new_ary = [] | |
# iterate through an array | |
self.each do |ar| | |
case ar | |
when Fixnum | |
new_ary << ar | |
when Array | |
new_ary += ar.flatten_array | |
else | |
# Raise if invalid type object found, | |
# considering only Fixnum and Array is valid | |
raise InvalidArrayItemFound, 'Not an integer or (nested) array item' | |
end | |
end | |
new_ary | |
end | |
end | |
# Mixing the module with array class! | |
class Array | |
include MixArrayFlattener | |
end | |
# Output: | |
# for invalid array element, this should raise error | |
# [1,2, [2,3], [7,9,8,78, [78,89,6,8,4,[1,3,2,6]]], [43,89,90,'s']].flatten_array | |
# => MixArrayFlattener::InvalidArrayItemFound: Not an integer or (nested) array item | |
## for valid array element, this should flatten the array | |
#[1,2, [2,3], [7,9,8,78, [78,89,6,8,4,[1,3,2,6]]], [43,89,90,1212121],23232322,0,9,6].flatten_array | |
# => [1, 2, 2, 3, 7, 9, 8, 78, 78, 89, 6, 8, 4, 1, 3, 2, 6, 43, 89, 90, 1212121, 23232322, 0, 9, 6] | |
# [1, 3].flatten_array | |
# => [1, 3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment