Forum: Ruby Unless Expression Parsing

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
E7559e558ececa67c40f452483b9ac8c?d=identicon&s=25 Gary Wright (Guest)
on 2007-04-20 03:54
(Received via mailing list)
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 Wright
Feee221f9eb7818d90625ea141bfd60c?d=identicon&s=25 bbiker (Guest)
on 2007-04-20 05:52
(Received via mailing list)
On Apr 19, 9:53 pm, Gary Wright <gwtm...@mac.com> wrote:
>
> Gary Wright

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
E7559e558ececa67c40f452483b9ac8c?d=identicon&s=25 Gary Wright (Guest)
on 2007-04-20 07:06
(Received via mailing list)
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 topic is locked and can not be replied to.