在调用方法时,我无法在以下情况中省略括号:
t=[]
t.push {}
# => [] # I expected [{}]
t.push({})
# => [{}]
Run Code Online (Sandbox Code Playgroud)
我应该采用什么规则来避免这种情况?
当您{}作为唯一参数传递时(因此调用中没有逗号),Ruby无法判断您是否表示空哈希或空块,因此您需要使用括号来区分它:
t.push(){}
t.push({})
Run Code Online (Sandbox Code Playgroud)
在其他情况下,好的经验法则是,如果直接使用方法调用作为参数,则需要使用括号
method arg0, arg1, other_method(arg01, arg02), arg2, arg3
Run Code Online (Sandbox Code Playgroud)
当您的方法调用更加嵌套时,最好使用局部变量(或重新考虑您的接口)来备用方法调用,即
arg3 = other_method arg01, arg02
methods arg0, arg1, arg3, arg3, arg4
Run Code Online (Sandbox Code Playgroud)