Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # CHANGE THIS ARRAY TO CUSTOMIZE TEST
- # this default array was grabbed from the instructions
- original_array = [[1,2,[3]],4]
- def flatten_array(array)
- temp_array = []
- # loop through provided array
- array.each do |item|
- # check if the given index is an array
- if item.class == Array
- # if so, run parent function on this item ---> RECURSIVE
- arr = flatten_array(item)
- # push each item to temp_array
- arr.each do |i|
- temp_array.push(i)
- end
- else
- # if item is not an array, push directly to temp_array
- temp_array.push(item)
- end
- end
- return temp_array
- end
- # demonstration
- # run "ruby main.rb" in the terminal to execute
- new_array = flatten_array(original_array)
- p new_array
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement