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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With