Ruby class variables Ruby class variables ruby ruby

Ruby class variables


To contrast @khelll's answer, this uses instance variables on the Class objects:

class Fish  # an instance variable of this Class object  @var = 'fish'  # the "getter"  def self.v    @var  end  # the "setter"  def self.v=(a_fish)    @var = a_fish  endendclass Trout < Fish  self.v = 'trout'endclass Salmon < Fish  self.v = 'salmon'endp Trout.v   # => "trout"p Salmon.v  # => "salmon"

Edit: to give instances read-access to the class's instance variable:

class Fish  def type_of_fish    self.class.v  endendp Trout.new.type_of_fish   # => "trout"p Salmon.new.type_of_fish  # => "salmon"


@var mentioned above is called class instance variable, which is different from instance variables... read the answer here to see the diff.

Anyway this is the equivalent Ruby code:

class Fish  def initialize    @var = 'fish'  end  def v    @var  endendclass Trout < Fish  def initialize    @var = 'trout'   endendclass Salmon < Fish  def initialize    @var = 'salmon'   endendputs Trout.new.vputs Salmon.new.v


Here's the version I ended up figuring out using hobodave's link:

class Fish  class << self    attr_accessor :var  end  @var = 'fish'  def v    self.class.var  endendclass Trout < Fish  @var = 'trout'endclass Salmon < Fish  @var = 'salmon'endputs (Trout.new).v   # => troutputs (Salmon.new).v  # => salmon

Notice that subclassing only requires adding an @var -- no need to override initialize.