Instance variable is not shared among methods

Viewed 52

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.

2 Answers

You're trying to define instance variable on the class level. Consider using @@price = true or cattr_accessor(:price) { true } from Active Support.

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
Related