Ruby class variables

docwhat picture docwhat · Jan 18, 2010 · Viewed 34.9k times · Source

The ruby class-instance stuff is giving me a headache. I understand given this...

class Foo
  @var = 'bar'
end

...that @var is a variable on the created class's instance.

But how do I create a sub-class overridable class variable?

Here is an example of what I would do in Python:

class Fish:
var = 'fish'
def v(self):
    return self.var

class Trout(Fish):
    var = 'trout'

class Salmon(Fish):
    var = 'salmon'

print Trout().v()
print Salmon().v()

Which outputs:

trout
salmon

How do I do the same thing in ruby?

Answer

glenn jackman picture glenn jackman · Jan 18, 2010

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
  end
end

class Trout < Fish
  self.v = 'trout'
end

class Salmon < Fish
  self.v = 'salmon'
end

p 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
  end
end

p Trout.new.type_of_fish   # => "trout"
p Salmon.new.type_of_fish  # => "salmon"