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