我知道许多 ruby 风格指南都坚持在方法定义 的方法参数周围使用括号。而且我理解有时方法调用在语法上需要括号。
但是谁能提供示例来说明为什么 Ruby 需要在方法定义的参数周围加上括号?基本上,除了“看起来更好”之外,我还在寻找其他原因。
最佳答案
如果你既没有括号也没有分号 as pointed out in this comment , 这将是模棱两可的。
def foo a end # => Error because it is amgiguous.
# Is this a method `foo` that takes no argument with the body `a`, or
# Is this a method `foo` that takes an argument `a`?
另外,当你想使用复合参数时,你不能省略括号:
def foo(a, b), c
p [a, b, c]
end
# => Error
def foo((a, b), c)
p [a, b, c]
end
foo([1, 2], 3) # => [1, 2, 3]
关于Ruby 将方法定义中的参数括起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14703024/