Open In App
Related Articles

Ruby | Array class flatten() function

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report
flatten() is an Array class method which returns flattened array i.e. a 1D array
Syntax: Array.flatten() Parameter: Array Return: 1D array
Example #1 :
# Ruby code for flatten() method
  
# declaring array
a = [[18, 22],
    [ 33, nil, 5, 6]]
  
# declaring array
b = [[[1, 4, 1, 1, 88, 9]]]
  
  
# flatten
puts "flatten : #{a.flatten()}\n\n"
  
# flatten
puts "flatten : #{b.flatten()}\n\n"

                    
Output :
flatten : [18, 22, 33, nil, 5, 6]

flatten : [1, 4, 1, 1, 88, 9]

Example #2 :
# Ruby code for flatten() method
  
# declaring array
a = [["abc", "nil", ],
    ["dog"]]
  
# declaring array
b = [[[["cow", nil, "dog"]]]]
  
  
# flatten
puts "flatten : #{a.flatten()}\n\n"
  
# flatten
puts "flatten : #{b.flatten()}\n\n"

                    
Output :
flatten : ["abc", "nil", "dog"]

flatten : ["cow", nil, "dog"]



Last Updated : 08 Jan, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads