0

I'm trying to understand inheritance:

class Car
  @@wheels = 4
  def wheel
    @@wheels
  end
end

class StretchLimo < Car
  @@wheels = 6
  def whee
    @@wheels
  end
  def turn_on_television
  end
end

I instantiate some objects like so:

moe = Car.new
larry = StretchLimo.new

When I do moe.wheel, I get 6, when I'm expecting 4.

The Ruby tutorial I'm following says it's supposed to be 4. Larry.whee should obviously return 6.

By the way, the "wheel" and "whee" functions I added so I could see the values. Can anyone explain what's wrong here?

Breno Gazzola
  • 2,092
  • 1
  • 16
  • 36
E L
  • 59
  • 2

2 Answers2

1

Class variables in Ruby are strange and confusing.

An idiomatic way to implement what you want is this:

class Car
  def wheels
    4
  end
end

class StretchLimo < Car
  def wheels
    6
  end
end

Car.new.wheels #=> 4
StretchLimo.new.wheels #=> 6

Whats happening is that class variables are shared between all instances of a class. Because StrechLimo is a subclass of Car instances of StrechLimo also see this variable.

Community
  • 1
  • 1
levinalex
  • 5,889
  • 2
  • 34
  • 48
  • this is almost certainly not the preferred method...see http://stackoverflow.com/questions/2441524/closest-ruby-representation-of-a-private-static-final-and-public-static-final – Sam Grondahl Sep 05 '12 at 21:29
0

@@ is a class variable so it is shared across all objects instantiated from a given class and all derived class. Because Ruby is interpreted, until you instantiate a StretchLimo object, it should not look at any of the StretchLimo code, so if you did the following:

moe = Car.new
moe.wheel # should give 4
larry = StretchLimo.new
moe.wheel # should give 6

Because when the StretchLimo gets interpreted it updates the @@wheels class variable to be 6. On the other hand, if you declared "wheels" with only one "@" (@wheels), it would be an instance variable specific to the object itself, and you would get your preferred behavior.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Sam Grondahl
  • 2,397
  • 2
  • 20
  • 26
  • this is not actually true. `moe.wheel` gives 6 on the second line. try it. – levinalex Sep 05 '12 at 18:47
  • depends on directory structure and how interpreted. I do get moe.wheel -> 6 if both classes are defined in the same file and I load from there, but this is not the case if I force the interpreter to load these classes sequentially. Regardless, the preferred method is to use instance variables – Sam Grondahl Sep 05 '12 at 21:26