ruby 带有可选参数的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35747905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
A method with an optional parameter
提问by TamRock
Is there a way to make a method that can accept a parameter, but can also be called without one, in which case the parameter is regarded nillike the following?
有没有办法制作一个方法可以接受一个参数,但也可以不带参数调用,这种情况下参数被认为是nil这样的?
some_func(variable)
some_func
回答by sawa
def some_func(variable = nil)
...
end
回答by bogl
Besides the more obvious option of parameters with default values, that Sawahas already shown, using arrays or hashes might be handy in some cases. Both solutions preserve nilas a an argument.
除了更明显的带有默认值的参数选项之外,Sawa已经展示过,在某些情况下使用数组或散列可能很方便。两种解决方案都保留nil作为参数。
1. Receive as array:
1. 接收为数组:
def some_func(*args)
puts args.count
end
some_func("x", nil)
# 2
2. Send and receive as hash:
2. 以散列形式发送和接收:
def some_func(**args)
puts args.count
end
some_func(a: "x", b: nil)
# 2
回答by Charmi
You can also use a hash as argument and have more freedom:
您还可以使用哈希作为参数并拥有更多自由:
def print_arg(args = {})
if args.has_key?(:age)
puts args[:age]
end
end
print_arg
# =>
print_arg(age: 35, weight: 90)
# => 35

