hsvahkj
hsvahkj

Reputation: 41

Instance variable is not shared among methods

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

Answers (2)

Sergio Tulentsev
Sergio Tulentsev

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

Alexander Zagaynov
Alexander Zagaynov

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

Related Questions