How can I check whether a variable is defined in Ruby? Is there an isset
-type method available?
相关问题
- C# how to invoke a field initializer using reflect
- 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
相关文章
- 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
- Are GetCallingAssembly() and GetExecutingAssembly(
- How to detect if an element exists in Watir
- uninitialized constant Mysql2::Client::SECURE_CONN
Also, you can check if it's defined while in a string via interpolation, if you code:
The system will tell you the type if it is defined. If it is not defined it will just return a warning saying the variable is not initialized.
Hope this helps! :)
This is the key answer: the
defined?
method. The accepted answer above illustrates this perfectly.But there is a shark, lurking beneath the waves...
Consider this type of common ruby pattern:
method2
always returnsnil
. The first time you callmethod1
, the@x
variable is not set - thereforemethod2
will be run. andmethod2
will set@x
tonil
. That is fine, and all well and good. But what happens the second time you callmethod1
?Remember @x has already been set to nil.
But method2
will still be run again? If method2 is a costly undertaking this might not be something that you want.Let the
defined?
method come to the rescue - with this solution, that handles that particular case.The devil is in the details: but you can evade that lurking shark by just getting "a bigger boat".