On Mon, Sep 10, 2012 at 4:57 PM, IƱaki Baz Castillo <[email protected]> wrote:
> Two similar cases (same behavior):
>
> 1)
> ---------------------
> my_var = 123 if false
>
> puts my_var
> => nil
> ---------------------
>
> 2)
> ---------------------
> if false
> my_var = 123
> end
>
> puts my_var
> => nil
> ---------------------
>
> Somebody could expect that "puts my_var" should raise "NameError:
> undefined local variable or method `my_var'" in both cases.
The issue with expectations is that sometimes they aren't met. :-)
> So I can understand that in case 1) the Ruby interpreter knows about
> my_var variable since it reads it before checking the "if". But in
> case 2) It seems that my_var variable is known when the script/file is
> loaded since the interpreter will never run into the "if false"
> statement.
>
> Am I right? Thanks a lot.
Mostly. The variable is known from the lexical position in the code
where it is defined - even if that code is not executed - as you found
out:
> --------------------
> puts "1: defined? my_var: #{(defined? my_var).inspect}"
>
> if false
> my_var = 123
> end
>
> puts "2: defined? my_var: #{(defined? my_var).inspect}"
>
>
> =>
> 1: defined? my_var: nil
> 2: defined? my_var: "local-variable"
> --------------------
That's also the reason why these behave differently although they seem
to do the same:
$ ruby -e 'if x.nil?; x=123; end; p x'
-e:1:in `<main>': undefined local variable or method `x' for
main:Object (NameError)
$ ruby -e 'x=123 if x.nil?; p x'
123
Kind regards
robert
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
-- You received this message because you are subscribed to the Google Groups
ruby-talk-google group. To post to this group, send email to
[email protected]. To unsubscribe from this group, send email
to [email protected]. For more options, visit this
group at https://groups.google.com/d/forum/ruby-talk-google?hl=en