Forum: Ruby Two similar sentences have different behaviour. Is it ok?

Posted by "Алексей Черненков" <laise@pisem.net> (Guest)
on 2013-02-15 13:36
(Received via mailing list)
Two similar sentences have different behaviour. Is it ok?

Compare:

1.9.3p374 :001 > a = 123 unless defined? a
 => nil
1.9.3p374 :002 > a
 => nil

but...

1.9.3p374 :003 > unless defined? b
1.9.3p374 :004?>   b = 123
1.9.3p374 :005?>   end
 => 123
1.9.3p374 :006 > b
 => 123
Posted by Hans Mackowiak (hanmac)
on 2013-02-15 13:41
its because is the first sample a= is parsed first so it knows that its 
an local variable, thats why  defined? a returns true

using defined is not an good idea, showing this sample:

if false
  a = 2
end
a #=> nil
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.