David Masover
8/21/2008 2:11:00 AM
On Wednesday 20 August 2008 00:38:43 Ron Green wrote:
> class Body
> @feet = 2
> puts "We have #{@feet} feet"
> def initialize
>
> end
> def report
> puts "We have #{@feet} feet"
> end
> end
>
> b=Body.new
> b.report
>
> Why is it in the above class the first puts prints correctly but the second
> puts doesn't have a value for the instance variable?
Well, in this case, you're defining an instance variable... on Body, the
class:
> class Body
> @feet = 2
You see, classes are objects, too. You can treat them like normal objects:
b = Body
c = b.new
The normal way to do what I think you're wanting to do here is:
class Body
def initialize
@feet = 2
end
end
By the way, you can leave out initialize if you have nothing to initialize.
Of course, if you're only supporting humans, you could do this:
class Body
FEET = 2
def report
puts "We have #{FEET} feet"
end
end
One more thing: I don't often use instance variables directly. That gives me
more flexibility -- I can do something like this:
class Body
attr_reader :feet
def initialize
@feet = 2
end
def report
puts "We have #{feet} feet"
end
end
That way, I could change to using a constant without touching the "report"
method. The next version would look like this:
class Body
FEET = 2
def feet
FEET
end
...
end
But it's getting a bit silly talking about feet, so I'll stop.