# Question about using the Factory Pattern

**URL:** <https://www.ruby-forum.com/t/question-about-using-the-factory-pattern/171115>\
**Category:** Ruby\
**Created:** [June 26, 2009, 4:49pm UTC](https://www.ruby-forum.com/t/question-about-using-the-factory-pattern/171115 "2009-06-26T16:49:47Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![leveille](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/a88e57/32.png) [@leveille](https://www.ruby-forum.com/u/leveille)\
**Post date:** [June 26, 2009, 4:49pm UTC](https://www.ruby-forum.com/t/question-about-using-the-factory-pattern/171115/1 "2009-06-26T16:49:47Z")

</div>

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!

---

<div class="post-metadata">

**Author:** ![leveille](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/a88e57/32.png) [@leveille](https://www.ruby-forum.com/u/leveille)\
**Post date:** [June 26, 2009, 5:16pm UTC](https://www.ruby-forum.com/t/question-about-using-the-factory-pattern/171115/2 "2009-06-26T17:16:34Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![leveille](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/a88e57/32.png) [@leveille](https://www.ruby-forum.com/u/leveille)\
**Post date:** [June 26, 2009, 5:20pm UTC](https://www.ruby-forum.com/t/question-about-using-the-factory-pattern/171115/3 "2009-06-26T17:20:44Z")

</div>

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