Subject: Simple question
Date: Sat 03 Nov 12 03:52:00AM +0900
Quoting August Y. ([email protected]):
def coords
x=rand(1000)
y=rand(1000)
z=rand(1000)
lo=[x,y,z]
puts lo
end
def size
pi=Math::PI
area=pi*(radus^2) <----error cant find radus?
If you want to refer to your global variable, you must always use the
dollar sign:
area=pi*($radus^2)
If you just use ‘radus’, you refer to a different variable, which in
this case is not defined. The scope of variables whose first character
is a lower-case letter is limited to the method body.
volume = 4/3*pi*(radus^3)
puts volume
puts radus
puts area
end
def landmass
landmass=size.area*0.33 <— why is this wrong?
size is a method. If you want the method to return the area, you must
rewrite it as
def size
pi=Math::PI
area=pi*($radus^2) <----error cant find radus?
volume = 4/3pi($radus^3)
puts volume
puts $radus
puts area
return area
end
and then you can write the line as
landmass=size()*0.33
which means: assign to variable landmass the return value of methods
size, multiplied by 0.33.
puts landmass
this line just prints the value on screen, but you want to return the
value. You must add
return landmass
If you do not specify an explicit return statement, methods return the
result of the last operation that has been executed. The #puts method
returns nil, so your two methods return nil.
Note that it is not the best thing to use a global variable. Since the
variable is accessed only within the instance methods of a class, it is
more appropriate to use a class instance variable (in all places,
write @radus instead of $radus).
end
t=Test.new
puts t.landmass
end
You have to understand better the concepts of classes, instances,
methods, There are dozens of different ways of doing things in Ruby,
but I would write your class by using class instance variables for
radus, area, volume, landmass.
Try again!
Carlo