Define_method with block_given?

for some reason, I want to change following code:

class A
  def method_name(*args)
    if block_given?
      # do something with the block
      yield(*args)
      :block_is_given
    else
      # do other stuff
      :block_not_given
    end
  end
end

to this code:

class A
  %w(a b c d).each do |method_name|
    define_method(method_name) do |*args|
      if block_given?
        # do something with the block
        yield(*args)
        :block_is_given
      else
        # do other stuff
        :block_not_given
      end
    end
  end
end

But, I get this,

A.new.a #=> :block_not_given
A.new.a { "Hello World" } #=> :block_not_given

did I miss something?
How do I can get

A.new.a { "Hello World" }

to produce #=> :block_is_given and executes the block?

···

--
Posted via http://www.ruby-forum.com/.

block_given? gets confused about what context it should be looking in. To
get around it, just explicitly accept a block.

class A
%w(a b c d).each do |method_name|
   define_method(method_name) do |*args, &block|
     if block
       # do something with the block
       block.call(*args)
       :block_is_given
     else
       # do other stuff
       :block_not_given
     end
   end
end
end

A.new.a # => :block_not_given
A.new.a { "Hello World" } # => :block_is_given

···

On Sun, Jan 22, 2012 at 12:38 AM, Adit Cahya Ramadhan Adit < matematika.adit@gmail.com> wrote:

for some reason, I want to change following code:

class A
def method_name(*args)
   if block_given?
     # do something with the block
     yield(*args)
     :block_is_given
   else
     # do other stuff
     :block_not_given
   end
end
end

to this code:

class A
%w(a b c d).each do |method_name|
   define_method(method_name) do |*args|
     if block_given?
       # do something with the block
       yield(*args)
       :block_is_given
     else
       # do other stuff
       :block_not_given
     end
   end
end
end

But, I get this,

A.new.a #=> :block_not_given
A.new.a { "Hello World" } #=> :block_not_given

did I miss something?
How do I can get

A.new.a { "Hello World" }

to produce #=> :block_is_given and executes the block?

--
Posted via http://www.ruby-forum.com/\.

Thanks, that solve the problem.

···

--
Posted via http://www.ruby-forum.com/.