Question about using the Factory Pattern

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.

I was told I could use the factory pattern -

class FactoryClass
def self.create_object(params)
FactoryClass.new(params)
end
end

but I can’t put it together. Could someone give me a hint? Thank you!

Hi –

On Fri, 26 Jun 2009, Jason L. wrote:

def conversion_factor(unit)
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

Can’t you just tell it to?

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

David

I see. That is amazingly simple. Exactly what I need. Thank you very
much!