Hi --

On Fri, 26 Jun 2009, Jason Lillywhite wrote:

> I'm trying to create a method that returns a new object of the same
> class it is in. Here is my code (for doing a simple unit conversion from
> any length units to meters):
>
> class Unit
>  def initialize(n)
>    @unit = n[/[a-z]+/]
>    @value = n.to_f
>  end
>
>  def conversion_factor(unit)
>    #... converts to base units, meters for now
>  end
>
>  def base
>    new_n = (@value * conversion_factor(@unit)).to_s + " m"
>  end
> end
>
> So I can do n1 = Unit.new('5 ft')
>
> Then n1.base will return the string "1.523999 m"
>
> But what I want is for that to automatically become one of my Unit
> objects, not just a string.

Can't you just tell it to?

   def base
     self.class.new("#{@value * conversion_factor(@unit)} m")
   end


David

-- 
David A. Black / Ruby Power and Light, LLC
Ruby/Rails consulting & training: http://www.rubypal.com
Now available: The Well-Grounded Rubyist (http://manning.com/black2)
"Ruby 1.9: What You Need To Know" Envycasts with David A. Black
http://www.envycasts.com