Reputation: 41
Why instance variable is not working in Ruby on rails?
Here is my code:
class books
@price = true
def new
p(@price)
end
end
In console it prints nil
why? I want it to be printed true.
Upvotes: 2
Views: 158
Reputation: 230561
In console it prints
nil
why? I want it to be printed true.
That instance variable assignment is on another object, the class itself. Naturally, an object (instance of a class) can't see instance variables of another object (the class). Instead, you can set it on the instance level
class Books
def initialize
@price = true
end
def hello
p @price
end
end
Upvotes: 2
Reputation: 83
You're trying to define instance variable on the class level. Consider using @@price = true
or cattr_accessor(:price) { true }
from Active Support.
Upvotes: 3