Unless Expression Parsing

I just came across an unexpected parsing problem:

x = 3 unless true # parses just fine, x = nil

p(3 unless true) # parser chokes on unless

p((3 unless true)) # OK, ‘nil’ is printed

This seems like a bug in the parser rather than a real
syntax problem, but maybe I’m missing something?

Gary W.

On Apr 19, 9:53 pm, Gary W. [email protected] wrote:

Gary W.

in irb:

x = 3 unless true => nil

x => nil # x declared as a nil
object since it was never assigned an object
p 3 unless true => nil

p (( 3 unless true)) => nil # you’re asking for the result
of ‘3 unless true’, )

p nil => # no result since p did
nothing

3 unless true => # the result is nil but not
captured
so
p (3 unless true) => # no result since you are asking
p to print nothing

Note:

the above is equivalent to
unless true so ‘p 3’ never gets
interpreted and nothing happens
p 3
end

On Apr 19, 2007, at 11:50 PM, bbiker wrote:

p (( 3 unless true)) => nil # you’re asking for the result
of ‘3 unless true’, )

if ‘x unless y’ is a valid expression then why is the extra set
of parenthesis needed when that expression is used as a method argument?

foo(x unless y) # syntax error
foo((x unless y)) # not a syntax error

This seems to be a problem with any of the statement modifier forms:
if, rescue, while, until.

Looking at parse.y it seems that the grammar differentiates between
arguments and statements. Adding the parens forces the statement to
become an expression.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs