question about using the Factory Pattern

J

Jason Lillywhite

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!
 
D

David A. Black

Hi --

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
 
J

Jason Lillywhite

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!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,059
Latest member
cryptoseoagencies

Latest Threads

Top