How to access a class variable from the outside in ruby?
Use class_variable_get
to access a class variable outside of a class:
class Foo @@a = 1endFoo.class_variable_get(:@@a)=> 1
For most cases, class instance variables are preferred to class variables. The latter are prone to all manner of strange behaviour when used with inheritance.
Consider:
class Book @book_count = 0 @all_books = [] class << self attr_reader :book_count attr_reader :all_books end # further code omitted.end
With this code Book.book_count and Book.all_books get the expected data.
You can use class_eval
to evaluate a block of code within the scope of a specific class:
class Book @@bookCount = 1endBook.class_eval '@@bookCount'# => 1
And just for fun... you can actually do all kinds of trickery with class_eval
such as define a new method in the class without monkey patching:
Book.class_eval { @@bookCount = 5 }Book.class_eval '@@bookCount'# => 5Book.class_eval do def self.hey_look_a_new_method return "wow" endendBook.hey_look_a_new_method# => "wow"