-1

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?

1 Answer 1

0

["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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.