Array Flatten does not work (Instance variable nil)
        Posted  
        
            by Nick
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Nick
        
        
        
        Published on 2010-05-21T18:59:22Z
        Indexed on 
            2010/05/24
            20:51 UTC
        
        
        Read the original article
        Hit count: 167
        
ruby
I was trying to write a simple array flatten method, but it does not work using instance variable. It works only using class variables. Can anyone tell me why? and how to make it work using instance variables.
 class Array
 @y = []
  def flatten_array
   self.each do |x|
    if x.class.to_s != 'Array'
    @y <<  x
     else
     x.flatten_array
    end
   end 
   return @y  
  end  
 end
 a =  [1,2,3,4,5]
 b =  [6,7,8]
 c =  [9,10]
 a1 = [12,13,a,b,c]
 puts a1.inspect
 b1 = a1.flatten_array
 puts b1.inspect
        © Stack Overflow or respective owner