说我有以下代码:
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"
}
答案 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