Ruby version: ruby 2.6.7p197 (2021-04-05 revision 67941) [x86_64-linux]
Rails gem version: 6.0.1
Simple question, I have this example on rails console
As expected, if I try to call a non existent variable, I got an error
irb(main):007:0> value
# Traceback (most recent call last):
# 2: from (irb):7
# 1: from (irb):7:in `rescue in irb_binding'
# NameError (undefined local variable or method `value' for main:Object)
But if I try to do the following example
(value = 1) if value.present?
It returns nil for some reason, the first scenario this happenned there was no parenthesis, I thought it was defining the variable and then returning a value of nil, but then I tried with it and just happened again (I tried other variable because ruby counted that as a defined variable)
OBS: I tried the same scenario on raw irb and it raised me an error, this only happens on rails console
EDIT: It only raised an error because I didn't realized that '.present?' is a rails method, but if I change my syntax to
(value = 1) if value
the same behaviour happens
Why does that happen? Shouldn't a NameError be raised?
NoMethodErrordid it? Becausevalue = 1 if value.nil?works just fine. The parser recognizes the firstvalueand initializes asnilthen processes the right hand side. e.g.b = 7 if 1 == 2; b #=> nilvalueassignment, it treats it as a local variable even though the assignment has not occurred yet. Then the interpreter sweeps through and it evaluates the modifieriffirst (as it should) and sincevaluehas already been determined to be a local variable (albeit without a value) there is noNameError.