Quick actions

cmd+k|ctrl+k

Navigation

Languages

flatten_array

Snippet info

Language

Ruby

Visibility

public

Author

khai.le

Created

2016-08-09T08:19:00Z

Updated

2016-08-09T08:35:44Z

# I use glot.io instead of gist.github so you can execute the code 
# directly in browser
def flatten(array)
  raise ArgumentError, "array must not be nil" if array.nil?
  array.inject([]) do |result, element|
    result = if element.kind_of?(Array)
      element = flatten(element)
      result.concat(element)
    else
      result << element
    end
  end
end

test_array = [[1,2,[3]],4, [5,[6],[]]]
expected_array = [1,2,3,4,5,6]

array = flatten(test_array)
if expected_array == array
  print("#{array}\n")
  puts "Work as expected"
else
  raise "Didn't work"
end

INFO