From: Doug Glidden <41mortimer@...> Date: 2008-09-16T00:39:00+09:00 Subject: Re: Need someone who can help Dot Baiki wrote: > Hey! Amazing quick response! Outstanding. Sweet solutions! Will continue > reading my books I bought. Really cool. Thanks so much. This is what I > made now: > > --- begin --- > #!/usr/bin/env ruby > > class AreaOfCircle > > PI = 3.14159265 > > def initialize(radius) > @radius = radius > @area = nil > end > > def calc_area(radius) > @area = PI * @radius**2 > end > end > > print 'Enter radius of circle: ' > radius = gets.to_f > puts "You entered: #{radius}" > > instance = AreaOfCircle.new(radius) > screen_output = instance.calc_area(radius) > puts "Result: #{screen_output}" > --- end --- > > You know, the cool thing is that I really soooooon will understand Ruby > and its beauty :-) > > Baiki Baiki, I think you might end up getting surprised by what happens when you do this. For instance, consider the results of the following code, given your existing AreaOfCircle class (of which I really dislike the name, but never mind that for now): circle = AreaOfCircle.new 5 # circle has @radius=5, @area=nil area = circle.calc_area 3 # assigns @area=78.540... (25*PI), i.e. the radius # parameter is completely ignored So get rid of the completely unnecessary parameter for calc_area. Furthermore, the user probably doesn't want to have to remember to manually call for the area to be calculated when he creates a circle, so just do that in your constructor. Add accessors for @radius and @area and you're really cookin'. It might look something like this: class MyCircle attr_accessor :radius, :area PI = 3.14159265 def initialize(radius) @radius = radius calc_area end def calc_area @area = PI * @radius**2 end end Your program code could then look like this: print 'Enter radius of circle: ' radius = gets.to_f puts "You entered: #{radius}" instance = MyCircle.new(radius) screen_output = instance.area puts "Result: #{screen_output}" On the other hand, if all you're interested in is calculating the area and you don't actually need to store the information, use a mixin instead of a full-blown class: Module AreaOfCircle PI = 3.14159265 def calc_area(radius) PI * radius**2 end end # begin program code include AreaOfCircle print 'Enter radius of circle: ' radius = gets.to_f puts "You entered: #{radius}" screen_output = calc_area radius puts "Result: #{screen_output}" I know I threw a lot of stuff at you, so feel free to ask about anything you don't understand there. Doug -- Posted via http://www.ruby-forum.com/.