【问题标题】:How do I pass a block with other arguments?如何传递带有其他参数的块?
【发布时间】:2017-04-06 09:03:31
【问题描述】:
def test(args,&block)
  yield
end

test 1, {puts "hello"}

最后一行不起作用。如何传递带有其他参数的块?

【问题讨论】:

  • test(1){ puts "hello" }

标签: ruby yield


【解决方案1】:
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"

【讨论】:

    猜你喜欢
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多