Alan Coromano
Alan Coromano

Reputation: 26018

Local variables within if statement

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

Upvotes: 5

Views: 3216

Answers (1)

tadman
tadman

Reputation: 211610

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.

Upvotes: 1

Related Questions