Forum: Ruby define_method and blocks

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
582aeda5afc64739eeb5bf708f361587?d=identicon&s=25 David Carlton (Guest)
on 2007-07-21 14:31
(Received via mailing list)
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)

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 }

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)

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 Carlton
E34b5cae57e0dd170114dba444e37852?d=identicon&s=25 Logan Capaldo (Guest)
on 2007-07-21 14:58
(Received via mailing list)
On 7/21/07, David Carlton <> wrote:
> My first stab was this:
>     define_method(element) do
>     module_eval %Q{def #{element}(&block)
You're not really missing anything. This is an unfortunate oversight
been fixed in 1.9

meth { |&block| } is valid syntax in 1.9
This topic is locked and can not be replied to.