为什么 Ruby 的默认参数值没有分配给 nil 参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10506091/
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
Why do Ruby's default parameter values not get assigned to nil arguments?
提问by Patrick Smith
I'm new to Ruby and came across something that confused me a bit.
我是 Ruby 的新手,遇到了一些让我感到困惑的事情。
I set a default parameter value in a method signature.
我在方法签名中设置了默认参数值。
When calling the method, I passed a nilargument to that parameter.
调用该方法时,我nil向该参数传递了一个参数。
But the default value wasn't assigned; it remained nil.
但是没有分配默认值;它仍然存在nil。
# method with a default value of 1000 for parameter 'b'
def format_args(a, b=1000)
"\t #{a.ljust(30,'.')} #{b}"
end
# test hash
dudes = {};
dudes["larry"] = 60
dudes["moe"] = nil
# expecting default parameter value
puts "Without nil check:"
dudes.each do |k,v|
puts format_args(k,v)
end
# forcing default parameter value
puts "With nil check:"
dudes.each do |k,v|
if v
puts format_args(k,v)
else
puts format_args(k)
end
end
Output:
输出:
Without nil check:
larry......................... 60
moe...........................
With nil check:
larry......................... 60
moe........................... 1000
Is this expected behavior?
这是预期的行为吗?
What ruby-foo am I missing?
我错过了什么 ruby-foo ?
Seems like nilisn't the same "no value" that I'm accustomed to thinking of nullin other languages.
似乎与nil我习惯于null在其他语言中思考的“无价值”不同。
回答by Jeremy
The default parameter is used when the parameter isn't provided.
未提供参数时使用默认参数。
If you provide it as nil, then it will be nil. So yes, this is expected behavior.
如果您将其提供为nil,那么它将是nil。所以是的,这是预期的行为。
回答by Mike Bethany
If you want to set a default value, even if nil is passed, and still allow calling the method without an argument you need to set the default value to nil and use the "or equals" operator:
如果你想设置一个默认值,即使 nil 被传递,并且仍然允许在没有参数的情况下调用该方法,你需要将默认值设置为 nil 并使用“或等于”运算符:
def foo(bar=nil)
bar ||= "default value"
puts bar
end
回答by bonafernando
You can also use Ruby's splat operator (*) when calling that method:
您还可以*在调用该方法时使用 Ruby 的 splat 运算符 ( ):
dudes.each do |k,v|
puts format_args(k,*v)
end
Output:
输出:
larry......................... 60
moe........................... 1000
回答by steenslag
In Ruby, methods always return something. Sometimes, there is nothing to return (query in database turns up empty or something like that). nilis for those cases; It means something like 'nothing here', but it isa reference to an object. To get the behaviour you want, just pass no parameter.
在 Ruby 中,方法总是返回一些东西。有时,没有什么可返回(数据库中的查询变为空或类似的东西)。nil是针对这些情况的;它的意思是“这里什么都没有”,但它是对对象的引用。要获得您想要的行为,只需不传递参数。
def talk(msg="Hello")
puts msg
end
talk #=> "Hello"
回答by King'ori Maina
Try ... v.is_nil?in the if statement.
v.is_nil?在 if 语句中尝试 ...。

