in operator
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:
if [MS, AL, VA, TX, NJ, NY].include? state ...include?).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.
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:
x in array1 + array2x in array1 & array2x in array1 | array2in would bind more tightly than assignment, making it easy to assign a Boolean:flag = x in listin would bind more tightly than && and ||, simplifying such constructs as:if a in x || b in y ... if num > 1000 && num in primes...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