简体   繁体   English

为什么我们不能将带有其他参数的{}块传递给Ruby中的方法

[英]Why can't we pass a {} block with other parameters to a method in Ruby

When passing a block to a method in ruby with other parameters, why do we have to do it like that 当使用其他参数将块传递给使用ruby的方法时,为什么我们必须这样做

def method4(condition, attribute, &block)
    return "No Block" if block.nil?
    if condition
        block.call
    end
    puts attribute
end


method4(true,4) do
  puts "Hello World"
end

While we can't do it like that 虽然我们不能那样做

method4(true,4,{puts "Hello World"})

Apparently the latter is syntactically wrong 显然后者在语法上是错误的

You can only pass other objects as arguments, and blocks are not objects in Ruby. 您只能将其他对象作为参数传递,而块不是Ruby中的对象。 Blocks are syntactic constructs. 块是句法构造。

But they can easily be wrapped in objects, objects of Proc class. 但是它们可以轻松地包装在Proc类的对象中。 There is even a special shorthand operator for that: 甚至还有一个特殊的速记运算符:

method4(true, 4, &->{puts 'Hello World'})

A short explanation of above code: 上面的代码的简短说明:

->{} creates a Proc object around given block. ->{}在给定的块周围创建一个Proc对象。 As method4 requires a block, and not an object, you need to "unwrap" it to block once more, and that's why ampersand is there. 由于method4需要一个块而不是一个对象,因此您需要“解开”它以再次阻止,这就是与号存在的原因。 If the signature of method4 were instead: 如果改为method4的签名:

def method4(condition, attribute, proc) # note no ampersand

you would be able to omit the ampersand in method call too. 您也可以在方法调用中省略“&”号。

The correct syntax to call a method with block is method_name(arguments) { stuff() } 调用带块方法的正确语法是method_name(arguments) { stuff() }

In method4(true,4,{puts "Hello World"}) the curly braces gives you a syntax error, since, it could be a Hash object, like: method4(true, 4, {puts: "Hello World"}) method4(true,4,{puts "Hello World"}) ,花括号会给您带来语法错误,因为它可能是Hash对象,例如: method4(true, 4, {puts: "Hello World"})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM