2016-08-16 125 views
0

我有没有办法,我想通过一个可选的参数。默认情况下,我想将该参数设置为nil。这是我做的方式:可选参数/参数在红宝石

def my_function(arg1, arg2: nil) 
    # Do something 
end 

我把这个功能称为my_function(2, 5)。我得到一个错误,说: “错误的参数数量(给定2,预期1)”

我在这里做错了什么?我希望在某些调用期间为arg2传递一个值,并且希望在其他情况下为零。所以当我没有为arg2传递一个值时,我的函数调用看起来像my_function(2)

+2

你也可以使用'创建my_function(2 ARG2:5)' –

回答

2

试用

def my_function(arg1, arg2 = nil) 
+1

太快... –

1

你定义了默认的关键字参数(VS一个位置参数)。您可以调用您用my_function(2)以及my_function(2, arg2: 5)定义的函数。如果你想用一个位置参数,你可以将它定义为def my_function(arg1, arg2 = nil)

这里是关键字参数的一些细节。 https://robots.thoughtbot.com/ruby-2-keyword-arguments