From: sto.mar@... Date: 2013-02-12T01:09:34+09:00 Subject: Re: elegant way to determine if something is defined Am 10.02.2013 21:17, schrieb Robert Klemme: > On Sun, Feb 10, 2013 at 4:09 AM, tamouse mailing lists > wrote: >> 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: > > You can use a rescue modifier: > > > Kind regards > > robert > > $ ruby -e 'b = a + 1 rescue 99; p b' > 99 Hmmm... very dangerous. That would catch all kinds of exceptions, not only the NameError: a = [] b = a + 1 # => TypeError: can't convert Fixnum into Array vs. a = [] b = a + 1 rescue 99 b # => 99 --