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?
相关问题
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
- reference to a method?
- ruby 1.9 wrong file encoding on windows
- gem cleanup shows error: Unable to uninstall bundl
相关文章
- C#中 public virtual string Category { get; }这么写会报错:
- Ruby using wrong version of openssl
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- “No explicit conversion of Symbol into String” for
- Segmentation fault with ruby 2.0.0p247 leading to
- How to detect if an element exists in Watir
- uninitialized constant Mysql2::Client::SECURE_CONN
A bit late but a working solution that also does not overwrite falsey values (including
nil
):So
false
variables will get overriddenWhile
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.
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
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.