如果尚未定义,则设置 Ruby 变量
在 Ruby 中,如何将变量设置为某个值(如果尚未定义),并保留当前值(如果已定义)?
In Ruby, how do you set a variable to a certain value if it is not already defined, and leave the current value if it is already defined?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
虽然
x ||= value
是一种表达“如果 x 包含 false 值,包括 nil (此构造中隐含的 if x 未定义,因为它出现在赋值的左侧),将值赋给 x",它就是这样做的。它大致等价于以下内容。 (但是,
x ||= value
不会像此代码可能那样抛出NameError
,并且它始终会为x 分配一个值
,因为此代码没有 - 重点是看到x ||= value
对于 x 中的任何 false 值都具有相同的作用,包括“默认”nil
value):查看变量是否有确实没有被赋值,请使用
已定义?
方法:但是,在几乎所有情况中,使用
已定义?
是代码味道。 小心权力。做明智的事情:在尝试使用变量之前给它们赋值:)快乐编码。
While
x ||= value
is a way to say "if x contains a falsey value, including nil (which is implicit in this construct if x is not defined because it appears on the left hand side of the assignment), assign value to x", it does just that.It is roughly equivalent to the following. (However,
x ||= value
will not throw aNameError
like this code may and it will always assign a value tox
as this code does not -- the point is to seex ||= value
works the same for any falsey value in x, including the "default"nil
value):To see if the variable has truly not been assigned a value, use the
defined?
method:However, in almost every case, using
defined?
is code smell. Be careful with power. Do the sensible thing: give variables values before trying to use them :)Happy coding.
所以
false
变量将被覆盖So
false
variables will get overridden由于您没有指定哪种变量:
但不建议使用局部变量执行此操作。
编辑:事实上 v=v 是不需要的
As you didn't specify what kind of variable:
Don't recommend doing this with local variables though.
Edit: In fact v=v is not needed
如果变量没有定义(声明?),它就不存在,如果声明了,那么你知道如何初始化它,对吧?
通常,如果我只需要一个我还不知道其用途的变量——我知道它永远不会用作布尔值——我通过将其值设置为 nil 来初始化它。然后您可以很容易地测试它是否已被更改,
仅此而已。
If the variable is not defined (declared?) it doesn't exist, and if it is declared then you know how you initialized it, right?
Usually, if I just need a variable whose use I don't yet know---that I know will never use as a Boolean---I initialize it by setting its value to nil. Then you can test if it has been changed later quite easily
that's all.