Project

General

Profile

Feature #12929

ternary should look ahead w/in a block (and not care about newlines)

Added by ag4ve (shawn wilson) almost 3 years ago. Updated over 2 years ago.

Status:
Assigned
Priority:
Normal
Target version:
-
[ruby-core:78107]

Description

foo = (bar ? 0 : 1) # works
foo = (bar ?
  0 : 1) # works
foo = (bar
  ? 0
  : 1) # doesn't work

Files

Screen Shot 2016-11-14 at 10.24.39.png (207 KB) Screen Shot 2016-11-14 at 10.24.39.png mutantkeyboard (Antonio Nesic), 11/14/2016 09:25 AM

History

Updated by duerst (Martin Dürst) almost 3 years ago

In Ruby, all operators have to be written at the end of the line to make it possible to distinguish between complete statements (with a missing semicolon) and continuations.

The only exception is the '.' operator, which is allowed to be on the next line to make method chaining look better, as follows:

array.map ...
     .select ...
     .reject ...
     .group ...
     .sort ...

What do you think is special about the ternary operator?

Updated by mutantkeyboard (Antonio Nesic) almost 3 years ago

Martin Dürst wrote:

In Ruby, all operators have to be written at the end of the line to make it possible to distinguish between complete statements (with a missing semicolon) and continuations.

The only exception is the '.' operator, which is allowed to be on the next line to make method chaining look better, as follows:

array.map ...
     .select ...
     .reject ...
     .group ...
     .sort ...

What do you think is special about the ternary operator?

I think that this is what he meant. If he uses IRB, then the syntax error comes up like:

SyntaxError: (irb):14: syntax error, unexpected '?', expecting ')'
    from /Users/antonionesic/.rvm/rubies/ruby-2.3.1/bin/irb:11:in `<main>'

But I have to agree. This is a SyntaxError, and not a bug.
Ticket should be closed.

Updated by nobu (Nobuyoshi Nakada) almost 3 years ago

  • Assignee set to matz (Yukihiro Matsumoto)
  • Status changed from Open to Assigned
  • Description updated (diff)
  • Tracker changed from Bug to Feature

It is not a bug, and easy to extend the parser to allow that syntax, but doesn't look nice to me.

Updated by matz (Yukihiro Matsumoto) over 2 years ago

I don't think it's worth modifying the syntax. If you want to write complex conditional code, use if-statement.

Matz.

Also available in: Atom PDF