Skip to content

Instantly share code, notes, and snippets.

@shtakai
Created November 7, 2017 11:59
Show Gist options
  • Save shtakai/63016190ab8a616b325aebd81855b1bd to your computer and use it in GitHub Desktop.
Save shtakai/63016190ab8a616b325aebd81855b1bd to your computer and use it in GitHub Desktop.
null created by shtakai - https://repl.it/NsTA/1
arr1 = [[1, 2, [3, 4], 5], 6]
arr2 = [[1, 2], 3]
arr3 = [1, [2]]
arr4 = [[1], 2]
arr5 = ["this", ["is", "that", ["Sushi"]], "car"]
arr6 = [["this"], ["is", "that", ["Sushi"]], "car"]
def flat_arr(arr, new_arr=[])
arr.each do |el|
if el.kind_of?(Array)
# puts "this is array.#{el} inspect it"
flat_arr(el, new_arr)
else
# puts "this is leaf. #{el}"
new_arr << el
end
end
new_arr
end
#flat_arr(arr1)
# test
puts "arr1: #{arr1} -> #{flat_arr(arr1)}"
puts " -> equals to flatten: #{flat_arr(arr1) == arr1.flatten}"
puts "arr2: #{arr2} -> #{flat_arr(arr2)}"
puts " -> equals to flatten: #{flat_arr(arr2) == arr2.flatten}"
puts "arr3: #{arr3} -> #{flat_arr(arr3)}"
puts " -> equals to flatten: #{flat_arr(arr3) == arr3.flatten}"
puts "arr4: #{arr4} -> #{flat_arr(arr4)}"
puts " -> equals to flatten: #{flat_arr(arr4) == arr4.flatten}"
puts "arr5: #{arr5} -> #{flat_arr(arr5)}"
puts " -> equals to flatten: #{flat_arr(arr5) == arr5.flatten}"
puts "arr6: #{arr6} -> #{flat_arr(arr6)}"
puts " -> equals to flatten: #{flat_arr(arr6) == arr6.flatten}"
@shtakai
Copy link
Author

shtakai commented Nov 7, 2017

ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]
   
arr1: [[1, 2, [3, 4], 5], 6] -> [1, 2, 3, 4, 5, 6]
 -> equals to flatten: true
arr2: [[1, 2], 3] -> [1, 2, 3]
 -> equals to flatten: true
arr3: [1, [2]] -> [1, 2]
 -> equals to flatten: true
arr4: [[1], 2] -> [1, 2]
 -> equals to flatten: true
arr5: ["this", ["is", "that", ["Sushi"]], "car"] -> ["this", "is", "that", "Sushi", "car"]
 -> equals to flatten: true
arr6: [["this"], ["is", "that", ["Sushi"]], "car"] -> ["this", "is", "that", "Sushi", "car"]
 -> equals to flatten: true
=> nil

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment