Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.72 KB | None | 0 0
  1. # CHANGE THIS ARRAY TO CUSTOMIZE TEST
  2. # this default array was grabbed from the instructions
  3. original_array = [[1,2,[3]],4]
  4.  
  5. def flatten_array(array)
  6. temp_array = []
  7. # loop through provided array
  8. array.each do |item|
  9. # check if the given index is an array
  10. if item.class == Array
  11. # if so, run parent function on this item ---> RECURSIVE
  12. arr = flatten_array(item)
  13. # push each item to temp_array
  14. arr.each do |i|
  15. temp_array.push(i)
  16. end
  17. else
  18. # if item is not an array, push directly to temp_array
  19. temp_array.push(item)
  20. end
  21. end
  22. return temp_array
  23. end
  24.  
  25. # demonstration
  26. # run "ruby main.rb" in the terminal to execute
  27. new_array = flatten_array(original_array)
  28. p new_array
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement