Jesus Castello is famous with his detailed guides about how to program in Ruby. This time we decided to share with you a neat method to check for defined variables in Ruby described in RubyGuides. Use it to simplify your work! Ruby has this
defined? keyword that helps you check if a variable is defined or not.
A few interesting points to note:
defined?is a keyword, not a method
defined?is one of the few things in Ruby that ends in a question mark, but doesn’t follow the usual convention to return either
defined?can tell the difference between a nil value & a variable that has never been set before
When working with variables what you want most of the time is to check for
nil, instead of whether or not a variable is defined. Or even better, convert the variable into a known class using a conversion method. Check here for more examples.
Find more about Ruby! Tips, methods, peculiarities, and advice – all we could gather is delivered in our blog post ‘All about Ruby‘!
If you need a good Ruby development agency that already knows all of the Ruby hacks and use them wisely, contact Syndicode!