Open In App
Related Articles

Ruby | Array class flatten() function

Improve Article
Improve
Save Article
Save
Like Article
Like

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"]

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 08 Jan, 2020
Like Article
Save Article
Previous
Next
Similar Reads