If-then-else Assignment Shortcut (#8)

Submitted by: Ron Hopper

This revision by: Ron Hopper

Date: Mon Mar 19 16:56:50 -0500 2007

ABSTRACT

There are assignment shortcuts for most binary operators, however, the ternary if-then-else operator does not have a shortcut for assignment. In some situations this shortcut makes a lot of sense and its lack is noticeable.

PROBLEM

There are frequently scenarios when a variable needs to be replaced by a modified version of itself or a default value if it is nil. Assignment in these scenarios is achieved using the ternary if-then-else operator to check for a nil value and supply a default. There is unnecessary duplication, however, in the common case that the variable being assigned to is the same one being checked, as in these examples:

page_title = page_title ? "Title: #{page_title}" : "Untitled"
tree_node = tree_node ? tree_node.next : root_node

PROPOSAL

Allow the assigment shortcut syntax for the ternary if-then-else operator, so that code previously written as:

page_title = page_title ? "Title: #{page_title}" : "Untitled"
tree_node = tree_node ? tree_node.next : root_node

can instead be written more meaningfully and succinctly as:

page_title ?= "Title: #{page_title}" : "Untitled"
tree_node ?= tree_node.next : root_node

ANALYSIS

The change is trivial, does not create any language conflicts that I am aware of, and makes the code more concise while improving readability.

IMPLEMENTATION

The syntax:

x ?= y : z

should be expanded to

x = x ? y : z

Comments

from Robert Dober, Fri Apr 13 09:43:43 -0400 2007

Hi just wanted to say that I voted for the RCR although it was not
posted to the ML before, but I still like the idea...
I guess when I read RCR#7 I made the same mistake as Matz and Tom did,
thinking that ||= will just do, actually I think that ?= will make
some code more readable.
I am an advocate of this RCR.
I did not strongly advocate this RCR however, as most importantly it
is not vital and shall therefore be treated as medium priority
feature, and secondly I think the discussion of an RCR on the Ruby ML
is an important feature, pity that the initiator did not know about
that.

Cheers
Robert

from Yukihiro Matsumoto, Sat Apr 14 11:20:13 -0400 2007

Hi,

I am not sure yet about the usecase for this new operator.  Besides
that the operator '?=" is used differently in languages

  * character '=' in the current Ruby
  * void check assignment in Eiffel

I am not convinced how much useful this is, considering

  x = x ? a : b

is only slightly longer than

  x ?= a : b

and the former is more unambiguous.

                                                        matz.


Return to top

Copyright © 2006, Ruby Power and Light, LLC