From: "Carlo E. Prelz" Date: 2013-02-10T15:39:45+09:00 Subject: Re: elegant way to determine if something is defined Subject: elegant way to determine if something is defined Date: dom 10 feb 13 12:09:02 +0900 Quoting tamouse mailing lists (tamouse.lists@gmail.com): > Something like: > > 1.9.3-head :065 > b = a + 1 > > raises an exception if a is not defined: > > NameError: undefined local variable or method `a' for main:Object > from (irb):65 > from /home/tamara/.rvm/rubies/ruby-1.9.3-head/bin/irb:16:in `
' > > Is there a more elegant way to check if a is defined besides wrapping > it in begin/rescue/end block? Something along the order of: > > Object.defined?('a') Your question has already been answered. I just wanted to add that, coming from compiled languages, I was used to having the class of problems you describe caught at compilation. With Ruby, you have the advantage of not needing to declare variables. This *great* advantage comes with the downside of having to wait until runtime to catch this family of problems. I got used to this. While I do not use unit tests (which constitute more code, and thus give you more occasions to drop in the occasional bug or two), I make sure my code can be tested in its functionality very often during development. Problems like the one you write about are tripped into, and the exception message exactly pinpoints where the problem is located, so that it can be quickly fixed. What I mean is that I don't see when you could need an undefined variable exception to be caught - more or less elegantly. An undefined variable should shout as loudly as it can, so that the code may be quickly corrected. Carlo -- * Se la Strada e la sua Virtu' non fossero state messe da parte, * K * Carlo E. Prelz - fluido@fluido.as che bisogno ci sarebbe * di parlare tanto di amore e di rettitudine? (Chuang-Tzu)