Related Articles

Related Articles

Ruby | Array class flatten() function
  • Last Updated : 08 Jan, 2020

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 :



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

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

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

Example #2 :

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

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

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :