如果尚未定义,则设置 Ruby 变量 [英] Set Ruby variable if it is not already defined

查看:43
本文介绍了如果尚未定义,则设置 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?

推荐答案

While x ||= value 是一种表达如果 x 包含假值,包括 nil(隐含在这个结构如果 x 未定义,因为它出现在赋值的左侧),为 x 赋值",它就是这样做的.

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.

大致等同于以下内容.(但是,x ||= value 不会像这个代码那样抛出 NameError可能,它总是会为 x 赋值 因为这段代码没有 - 关键是要看到 x ||= value 对于 x 中的 any 假值(包括默认值")的作用相同nil 值):

It is roughly equivalent to the following. (However, x ||= value will not throw a NameError like this code may and it will always assign a value to x as this code does not -- the point is to see x ||= value works the same for any falsey value in x, including the "default" nil value):

if !x
  x = value
end  

要查看变量是否真正没有被赋值,请使用defined?方法:

To see if the variable has truly not been assigned a value, use the defined? method:

>> defined? z
=> nil                                                                  
>> z = nil                                                              
=> nil                                                                  
>> defined? z                                                           
=> "local-variable"                                                     
>> defined? @z                                                          
=> nil                                                                  
>> @z = nil                                                             
=> nil                                                                  
>> defined? @z                                                          
=> "instance-variable" 

但是,几乎在所有情况下,使用 defined? 是代码异味. 小心电源.做明智的事情:在尝试使用变量之前先给它们值:)

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 :)

快乐编码.

这篇关于如果尚未定义,则设置 Ruby 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆