Editing Topic: RCR241 Project: RCR | RCRchive home

RCR 241: in operator

submitted by hal9000 on Sat Apr 10 2004 07:18:27 PM -0700

Status: pending


Abstract

in operator

Problem

Ruby allows calling include? on a collection to determine whether an item is in that collection. In essence, we can think of this as: container operator item

But there is nothing to do that in reverse order, syntactically speaking: item operator container

The issues I perceive are these:

  1. Sometimes literal collections are used, and the literal is long and distracting:
    if [MS, AL, VA, TX, NJ, NY].include? state ...
  2. Sometimes the collection may be an expression like array1 + array2 (making parentheses necessary when calling include?).
  3. It is mathematically backwards, in that the familiar "epsilon" set operator goes in the opposite order.
  4. It is sometimes conceptually backwards, because we want to focus our attention on the item rather than the collection.
  5. There is precedent for this operator in computing, since Pascal has had it from the beginning; and (I believe) Python does also.

Proposal

Make the (existing) keyword in represent an operator in a syntax-sugar fashion.

Just as for x in y is syntax sugar that invokes the standard iterator each, let x in y be syntax sugar that invokes the method include? on the operand.

Analysis

In other words, x in y would always mean exactly the same as y.include? x, even when y does not define an include? method.

By analogy, note that for x in y will fail if y does not define each.

Note that in is already a reserved word in Ruby (which Matz has said "will not go away"). We therefore don't have to add a new keyword.

Existing code will not break, as the tokens x in y are not meaningful in Ruby currently.

Use of the operator would be optional at the programmer's discretion, just as for may or may not be used in place of each.

I envision this expression always returning true or false, since as far as I know, that is what include? always does.

Obviously common uses might be in loops and conditionals:
words << (ch = STDIN.getc) until ch in ['.', ';', '!', '?']
or also
if digit in 0..4 then...

The biggest question I am aware of is: What should the precedence of this operator be?

I favor putting it at the same level as the comparison operators. Note the following:

Implementation

I'm not qualified to comment much here. It seems to me this should be a small change. in is already a keyword; I would expect we could assign it a precedence, add some yacc rules, and add a bit of code calling the include? method.


Back to RCRchive.


RCR Submission page and RCRchive powered by Ruby, Apache, RuWiki (modified), and RubLog