facebook

Check for defined variables in Ruby

Check for defined variables in Ruby
Average rating: 0
(0 votes)

Thanks! You’ve rated this material!

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 true or false
  • 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!

Rate this article, if you like it

Thanks! You’ve rated this material!

Got a project? Let's discuss it!

*By submitting this form you agree with our Privacy Policy.

Mailing & Legal Address

Syndicode Inc. 340 S Lemon Ave #3299, Walnut CA, 91789, USA

Visiting & Headquarters address
Kyiv Sofiivska 1/2a, 01001, Kyiv, Ukraine
Dnipro Hlinky 2, of. 1003, 49000, Dnipro, Ukraine
Email info@syndicode.com
Phone (+1) 9035021111