Project

General

Profile

Actions

Feature #10343

closed

Postfix notations for `when` and `else` inside `case` statement

Added by sawa (Tsuyoshi Sawada) over 9 years ago. Updated about 1 year ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:65528]

Description

In a case statement, the condition part (when ...) in the branches do not have the same length in general, and especially, else is much shorter than the conditions. So when we write the condition and the return value in a single line, they are not aligned, and are hard to read.

case foo
  when some_very_long_proc then "a"
  when short_regex then "bbb"
  when some_long_regex then "cc"
  else "dddd"
end

I propose to allow postfix notations with when and else (or otherwise) inside case statement as below:

case foo
  "a" when some_very_long_proc
  "bbb" when short_regex
  "cc" when some_long_regex
  "dddd" else
end

Pros are:

  1. Postfix notation does not require then or ;, so it is concise.

  2. The return values from the branches (e.g., "a", "bb", "ccc", "dddd") tend to be shorter and more uniformly lengthened than the conditions, hence they are somewhat close to being aligned naturally, making this easier to read.

  3. We are usually more interested in the return value than the condition of a branch, especially when we are reading someone's code and are trying to grasp what the case statement does or returns.

  4. This notation is closer to case-like conditional notations regularly used in mathematics:

         ┌ 1          (x = 0)
    x! = ┤
         └ x (x - 1)! (otherwise)
    

    So it would be easier to read for those who are familiar with mathematics.

Actions

Also available in: Atom PDF

Like1
Like0Like0Like0Like1Like0Like0Like0Like0