如何传递带有其他参数的块?
How do I pass a block with other arguments?
def test(args,&block)
yield
end
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
因此调用这些方法将 return 以下内容:
test("args")
#=> no block
test("args"){ "Hello World" }
#=> "Hello World"
def test(args,&block)
yield
end
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
因此调用这些方法将 return 以下内容:
test("args")
#=> no block
test("args"){ "Hello World" }
#=> "Hello World"