【发布时间】:2017-04-06 09:03:31
【问题描述】:
def test(args,&block)
yield
end
test 1, {puts "hello"}
最后一行不起作用。如何传递带有其他参数的块?
【问题讨论】:
-
test(1){ puts "hello" }
def test(args,&block)
yield
end
test 1, {puts "hello"}
最后一行不起作用。如何传递带有其他参数的块?
【问题讨论】:
test(1){ puts "hello" }
test(1){ puts "hello" }
或
test(1) do
puts "hello"
end
或
blk = proc{ puts "hello" }
test(1, &blk)
你可以看看这个https://pine.fm/LearnToProgram/chap_10.html
正如@Cary Swoveland 建议的那样,我们可以稍微深入一点。
任何 Ruby 方法都可以隐式接受一个块。即使您没有在方法签名中定义它,您仍然可以捕获它并进一步传递。
因此,考虑到这个想法,我们可以使用您的方法进行以下操作:
def test(args, &block)
yield
end
与
相同def test(args)
yield
end
和一样
def test(args)
block = Proc.new
block.call
end
当你有这个隐式块捕获时,你可能想要添加额外的检查:
def test(args)
if block_given?
block = Proc.new
block.call
else
"no block"
end
end
或
def test(args)
if block_given?
yield
else
"no block"
end
end
因此调用这些方法将返回以下内容:
test("args")
#=> no block
test("args"){ "Hello World" }
#=> "Hello World"
【讨论】: