【发布时间】:2017-12-14 20:34:57
【问题描述】:
我有以下代码
def thing(item: "yeah")
puts item == nil
end
def thing2(item: nil)
thing(item: item)
end
thing2()
我希望看到false,因为我希望传递给thing 的nil 被视为未定义的item 参数,但是,我看到true。我怀疑这是因为像 JS 一样,ruby 将 nil 与 undefined 分开。那么有没有办法可以将值默认为undefined 而不是nil?
我目前基于接受的答案的最终版本看起来像这样......
def default_item
"yeah"
end
def default_other
"other"
end
def thing(item: default_item(), other: default_other())
puts item + " " + other
end
def thing1(other: default_other())
thing(other: other)
end
def thing2(item: default_item())
thing(item: item)
end
thing1()
thing2()
thing1(other:"Is Other")
thing2(item:"Is Item")
# fail with argument exception
# thing1(item:"Not Item")
# thing2(other:"Not Other")
(返回值的方法更多是基于它需要实际返回一个实例值)
我仍然不喜欢到处都是item: default_item(),所以我愿意接受更好的解决方案。
【问题讨论】:
-
“我希望 nil 传递给 thing 并看到 false” – 嗯?如果
nil作为参数传递给thing,为什么你会期望它打印“false”?你字面意思检查你是否通过nil,所以它当然会打印“true”。 -
因为我希望方法调用中的关键字 param 设置它,因为它为空。所以我猜这不会发生,因为它只设置未定义且 null != undefined 的值。那么我该如何声明它,而不是 nil 它将是未定义的
-
@JörgWMittag 他希望
thing看到item是nil,并将其解释为item未设置,因此默认item为"yeah" -
@River 谢谢,是的,所以我有点理解为什么它没有,但现在我需要知道如何让它工作。我不想在所有调用 thing 方法的地方重新声明默认值。
-
让我们非常清楚 ruby 不是 javascript 并且“未定义”是一个运行时错误 (
NameError)。如果您考虑这种分离,那么我想是的,红宝石可以分离这些东西。如果您想要nil的默认值,那么在 thing 方法中这将是item ||= "yeah"。