The string for a symbol can be any sequence of characters. Thats why the basic
representation for a symbol is %s(...) or %'abc' The
colon-identifier-notation (:abc) is just a shortcut to cover the
most common case. For the same reason, the colon-operator is an allowed
shortcut, because this is also used often.

Here is a realistic example of using a symbol which has an operator:

Say I have an array of numbers and want to sum up the numbers, I can use the
standard function *reduce* like this


sum = [2,5,4].reduce(0,&:+) # sets sum to 11


The 0 is obviously the initial value of the counter. The second parameter of
reduce must be a object of type Proc (basically an anonymous method), which
expects one argument and applies itself to the receiver; in the case of summing
up, this Proc must add the next element to the running total. For generating
this Proc object, we start with a the symbol :+ and apply to it the
operator '&'. This operator implicitly invokes the method to_proc
on the symbol. This method is defined in the Symbol class and
returns a suitable Proc object.

While having symbols representing operators is not uncommon (I think you find it
in Lisp, Scheme, Smalltalk,...), I believe that the trick with the ampersand is
fairly unique to Ruby.

-- 
Ronald Fischer (Germany)


<https://forum.pspad.com/read.php?2,74180,74193>
PSPad freeware editor https://www.pspad.com

Odpovedet emailem