如何将块传递给子方法?

时间:2014-03-13 00:23:26

标签: ruby

说我有以下代码:

def a(n, m, &block)
  yield if block_given?
end

def a
  # My question is here. When a is called, block might be or might not be
  # given. Below line is obvious wrong. How to call b and properly pass 
  # block to b?
  b(1, 2, &block)
end

a  # call a without block

a { # call a with a block
    puts "in block"
}

1 个答案:

答案 0 :(得分:8)

a()接受一个块。它暗示是可选的,正如安德鲁马歇尔所指出的那样,如果没有给出,将作为&nil传递。

def b(n, m, &block)
  yield if block_given?
  puts "no block" if !block_given?
end

def a( &block )
  b(1, 2, &block)
end

a  # call a without block

a { # call a with a block
    puts "in block"
}

输出:

no block
in block