可选参数语法
Optional argument syntax
我在 this question 下找到这段代码,它检查是否有任何参数传递给方法:
def foo(bar = (bar_set = true; :baz))
if bar_set
# optional argument was supplied
end
end
此默认值中 ; :baz
的用途是什么,我会在什么情况下使用它?
想法是,只有当值未传递给 bar
参数时,才会计算 = (bar_set = true; :baz)
。
在Ruby中,连续多个表达式的return值为最后一个表达式的值。因此 = (bar_set = true; :baz)
将值 true
分配给 bar_set
,然后将 :baz
设置为 bar
的值(因为括号中的代码将计算为 :baz
, 这是最后一个表达式).
如果传递了参数,bar_set
将是 nil
而 bar
的值将是给定的值。
我在 this question 下找到这段代码,它检查是否有任何参数传递给方法:
def foo(bar = (bar_set = true; :baz))
if bar_set
# optional argument was supplied
end
end
此默认值中 ; :baz
的用途是什么,我会在什么情况下使用它?
想法是,只有当值未传递给 bar
参数时,才会计算 = (bar_set = true; :baz)
。
在Ruby中,连续多个表达式的return值为最后一个表达式的值。因此 = (bar_set = true; :baz)
将值 true
分配给 bar_set
,然后将 :baz
设置为 bar
的值(因为括号中的代码将计算为 :baz
, 这是最后一个表达式).
如果传递了参数,bar_set
将是 nil
而 bar
的值将是给定的值。