Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local variables within if statement

Tags:

ruby

ruby-2.0

I wonder, why is a visible?

if true
  puts 'true'
else
  puts 'false'
  a = 123
end

puts a # no error

# or 
# my_hash = {key: a}
# puts my_hash # :key => nil

But this causes an error, even though there will be 'true' shown

if true
  puts 'true'
else
  puts 'false'
  a = 123
end

puts a2 # boooooom
like image 581
Alan Coromano Avatar asked Nov 13 '22 08:11

Alan Coromano


1 Answers

Referencing a inside the if has the effect of declaring it as a variable if there is no method a= defined for the object.

Since Ruby does not require methods to be called using the same syntax as referencing a variable or assigning to one, it needs to make an assessment as to the nature of the token in question. If it could be a method call because a method with that name has been defined, then it will be interpreted as such. If no such method exists at the time the source is compiled, then it will be a variable by default.

like image 62
tadman Avatar answered Nov 15 '22 04:11

tadman