rubyclass-instance-variables

Class instance variable is coming as `nil` in instance method


I assigned a class instance variable as an array.

class Red
  @items = ["brinjal", "banana"]
  puts @items.inspect 
  def test
    puts @items.inspect
  end
end

p = Red.new # => prints ["brinjal", "banana"]
p.test # => prints nil

If I access an instance of the class, it returns nil. What is happening here?


Solution

  • ["brinjal", "banana"] is in @items of Red, a Class object.

    nil is in @items of p, a Red object.

    If you change all of your @ to @@, it will work, as those are always class-level. Or you could use a class-level accessor:

    class Red
      class << self
        attr_accessor :items
      end
      @items=[]
      @items<<"brinjal"
      @items<<"banana"
      puts items.inspect
      def test
        puts self.class.items.inspect
      end
    end