# Define\_method and blocks

**URL:** <https://www.ruby-forum.com/t/define-method-and-blocks/110024>\
**Category:** Ruby\
**Created:** [July 21, 2007, 2:31pm UTC](https://www.ruby-forum.com/t/define-method-and-blocks/110024 "2007-07-21T14:31:25Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![crucoba](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/e8c25b/32.png) [@crucoba](https://www.ruby-forum.com/u/crucoba)\
**Post date:** [July 21, 2007, 2:31pm UTC](https://www.ruby-forum.com/t/define-method-and-blocks/110024/1 "2007-07-21T14:31:25Z")

</div>

I’m trying to programmatically add methods taking a block to a class.  
Specifically I’m trying to write a method ‘define\_inline\_element’ that  
will let me type

define\_inline\_element :title

and create a method called ‘title’ in my class, with appropriate  
behavior, taking a block.

My first stab was this:

def self.define\_inline\_element(element)  
define\_method(element) do |&block|  
inline\_element(element.to\_s, &block)  
end  
end

but |&block| was syntactically invalid. Then I tried this:

def self.define\_inline\_element(element)  
define\_method(element) do  
inline\_element(element.to\_s) { yield }  
end  
end

but when I invoked one of my generated methods with a block, the block  
got thrown away and the yield call failed.

So now I’ve resorted to eval:

def self.define\_inline\_element(element)  
module\_eval %Q{def #{element}(&block)  
inline\_element("#{element}", &block)  
end}  
end

which works, but I don’t like eval as much as blocks.

Anything I’m missing? I’m using Ruby 1.8.2, if that matters. (Yes, I  
know I’m a few versions behind.)

David C.  
removed\_email\_address@domain.invalid

---

<div class="post-metadata">

**Author:** ![crucoba](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/e8c25b/32.png) [@crucoba](https://www.ruby-forum.com/u/crucoba)\
**Post date:** [July 21, 2007, 2:58pm UTC](https://www.ruby-forum.com/t/define-method-and-blocks/110024/2 "2007-07-21T14:58:27Z")

</div>

On 7/21/07, David C. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> My first stab was this:  
> define\_method(element) do  
> module\_eval %Q{def #{element}(&block)  
> removed\_email\_address@domain.invalid  
> You’re not really missing anything. This is an unfortunate oversight  
> that’s  
> been fixed in 1.9

meth { |&block| } is valid syntax in 1.9
