Skip to main content

Ruby flatten array method

In ruby programming language, flatten() array methods are used to flattening an self array. Parameters of this method are optional, This method are flattening array elements into one dimensional array when not providing parameter values. When provide parameter value this is indicated number of flattening level of dimensions. Syntax of this method as follows.

flatten → new array
flatten(level) → new array

Example of flatten() method

When the value of the given parameter is less than the internal dimension array, then resultant array share internal dimensions array by reference. let see an example.

# Our array
record  = ['a','b','c',[1,2,[true,false]]]

# flatten method
r1 = record.flatten()
r2 = record.flatten(1)

# Display record
print("Record : " ,record)
# Display result
print("\nr1 : " ,r1)
print("\nr2 : " ,r2)
Ruby flatten method example 2
Record : ["a", "b", "c", [1, 2, [true, false]]]
r1 : ["a", "b", "c", 1, 2, true, false]
r2 : ["a", "b", "c", 1, 2, [true, false]]

This method returns a new array. This method shares common objects by default when the array contains custom class objects.

class Test 
  # Define the accessor and reader of class Test
  attr_reader :a
  attr_accessor :a
  def initialize(a) 
    self.a = a
  end
end

# Objects
t1 = Test.new(10)
t2 = Test.new(4)

record = [1,2,[t1,t2],3]

# flatten an array
r = record.flatten()

print(r)
Ruby flatten method example 3
[1, 2, #<Test:0x0 @a=10>, #<Test:0x0 @a=4>, 3]

Above example is very useful when need to share object instance. But when we need to not share this instance so we can use Enumerable and convert object to array.

class Test 
  include Enumerable
  # Define the accessor and reader of class Test
  attr_reader :a
  attr_accessor :a
  def initialize(a) 
    self.a = a
  end
  def each
    yield a
  end
  def to_ary
      to_a
    end
end

t1 = Test.new(10)
t2 = Test.new(4)

record = [1,2,[t1,t2],3]

r = record.flatten()

print(r)
Ruby flatten method example 4
[1, 2, 10, 4, 3]




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment