在 Ruby 中:我在调用它时以某种方式给方法一个参数,但不知道在哪里。我认为这与块绑定有关?

In Ruby: I'm giving a method an argument somehow when calling it, but don't know where. I think it has something to do with block bindings?

抱歉不知道如何更好地陈述这个问题。

我注意到 {} 的块语法如何绑定到紧靠左侧的对象,然后注意到 do/end 绑定到该行开始的对象。在这个过程中,我注意到了这一点:

def a(*)
  puts "a: #{block_given?}"
end

def b 
  puts "b: #{block_given?}" 
end

a b {}
#=> b: true
#=> a: false
a b do end  
#=> b: false
#=> a: true

令人困惑的是我不需要方法 'b' 上的 (*) 运算符(或那里的任何参数)并且两个方法调用行都导致相同的错误。

我只是不确定如果我在方法 'a' 中没有 (*) 参数然后它说 "Wrong number of arguments 1 for 0" 会发生什么,但我传递的参数是什么?为什么只给 'a'?

a b {}       # a(b{})
a b do end   # (a(b)) do end

a(b do end)  # behaves like a b {}  

解析器将 { 紧密绑定到它前面的标记。如果省略方法参数周围的括号,花括号块将与最后一个参数关联 - 可能不需要。