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
defined?
is great, but if you are in a Rails environment you can also usetry
, especially in cases where you want to check a dynamic variable name:This is useful if you want to do nothing if it does exist but create it if it doesn't exist.
This only creates the new instance once. After that it just keeps returning the var.
As many other examples show you don't actually need a boolean from a method to make logical choices in ruby. It would be a poor form to coerce everything to a boolean unless you actually need a boolean.
But if you absolutely need a boolean. Use !! (bang bang) or "falsy falsy reveals the truth".
Why it doesn't usually pay to coerce:
Here's an example where it matters because it relies on the implicit coercion of the boolean value to its string representation.
defined?(your_var)
will work. Depending on what you're doing you can also do something likeyour_var.nil?
Here is some code, nothing rocket science but it works well enough
Clearly, the colouring code is not necessary, just a nice visualation in this toy example.
It should be mentioned that using
defined
to check if a specific field is set in a hash might behave unexpected:The syntax is correct here, but
defined? var['unknown']
will be evaluated to the string"method"
, so theif
block will be executededit: The correct notation for checking if a key exists in a hash would be: