# Re: Advice on using define\_method in ActiveRecord descendant

**URL:** <https://www.ruby-forum.com/t/re-advice-on-using-define-method-in-activerecord-descendant/69699>\
**Category:** Ruby\
**Created:** [September 23, 2006, 12:18am UTC](https://www.ruby-forum.com/t/re-advice-on-using-define-method-in-activerecord-descendant/69699 "2006-09-23T00:18:38Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![phrogz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/2acd7d/32.png) [@phrogz](https://www.ruby-forum.com/u/phrogz)\
**Post date:** [September 23, 2006, 12:18am UTC](https://www.ruby-forum.com/t/re-advice-on-using-define-method-in-activerecord-descendant/69699/1 "2006-09-23T00:18:38Z")

</div>

> for attr in [ :gross\_receipts, :number\_of\_owners,  
> :annual\_employee\_payroll, :uninsured\_subcontractors\_contract\_cost,  
> :insured\_subcontractors\_contract\_cost ] do  
> self.class\_eval do  
> define\_method("#{attr.to\_s}=(new\_value)") {  
> write\_attribute(attr, new\_value.to\_s.gsub(/,/, ‘’))  
> }  
> end  
> end

You’re not defining the method quite correctly. You want the new\_value  
param to be an argument to the block.

class Foo  
[:bar, :jim, :jam].each{ |method\_name|  
self.class\_eval{  
define\_method( “#{method\_name}=”){ |new\_value|  
puts "The new value for ‘#{method\_name}’ is " + new\_value.to\_s  
}  
}  
}  
end

f = Foo.new  
f.bar = 42  
#=\> The new value for ‘bar’ is 42

Also, there’s no reason to use #to\_s inside string interpolation; it  
happens automatically.

---

<div class="post-metadata">

**Author:** ![phrogz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/2acd7d/32.png) [@phrogz](https://www.ruby-forum.com/u/phrogz)\
**Post date:** [September 25, 2006, 5:14pm UTC](https://www.ruby-forum.com/t/re-advice-on-using-define-method-in-activerecord-descendant/69699/2 "2006-09-25T17:14:37Z")

</div>

Gavin,

Thanks - worked like a charm. Unfort. there aren’t any readily  
available examples of define\_method where parameters are used. Makes  
sense to me that these would be block parameters now though.

Again, thanks.  
Wes
