Submitted by: Ron Hopper
This revision by: Ron Hopper
Date: Mon Mar 19 16:56:50 -0500 2007
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.
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
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
The change is trivial, does not create any language conflicts that I am aware of, and makes the code more concise while improving readability.
The syntax:
x ?= y : z
should be expanded to
x = x ? y : z
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.
Copyright © 2006, Ruby Power and Light, LLC
Comments
from Robert Dober, Fri Apr 13 09:43:43 -0400 2007