How to access a class variable from the outside in ruby?

winterwolff picture winterwolff · Dec 7, 2016 · Viewed 8.8k times · Source

I'm trying to access a class variable from a method outside of the class.

This is my class:

class Book

  @@bookCount = 0
  @@allBooks = []

  def self.allBooks
    @@allBooks
  end

  def self.bookCount
    @@bookCount
  end

  attr_accessor :name,:author,:date,:genre,:rating

  def initialize(name, author, date, genre, rating)
      @name = name
      @author = author
      @date = date
      @genre = genre
      @rating = rating
      @@bookCount += 1
      @@allBooks << self
  end

end

This is the method trying to access the class variable @@bookCount

def seeBookShelf
  if @@bookCount == 0
    puts "Your bookshelf is empty."
  else
    puts "You have " + @bookCount + " books in your bookshelf:"
    puts allBooks
  end
end

When I try to execute the method I get this:

undefined local variable or method `bookCount' for main:Object (NameError)

How can I access bookCount from the outside?

Answer

Ilya picture Ilya · Dec 7, 2016

Use class_variable_get to access a class variable outside of a class:

class Foo
  @@a = 1
end

Foo.class_variable_get(:@@a)
=> 1