joesb.coe9
6/2/2006 3:23:00 AM
Dave Burt wrote:
> me@mikehogan.net wrote:
> >> There are certain other operators that call methods behind-the-scenes: +
> >> - * ** / % =~ == === <=> < <= > >= & | [] []= @+ @- @~. But you can see
> >> the pattern - they're all "operators" - symbols not words.
> >
> > So this list of operators, am i right in assuming that its defined in
> > the ruby interpreter in C code, and is not something that I can add to?
>
> That's right. It's part of Ruby's syntax.
>
> Cheers,
> Dave
It would be cool, if not chaos, if Ruby allowed one to define binary
operator (and also may be ternary, too?) like in Haskell.
Haskell allow one to create binary operator simply by naming a function
using only symbol.
So function named 'foo' is call as
(foo 1 2)
but function '+', '-->', '<~>' are call as
1 --> 2
You can also use 'foo' as operator by putting backquote around it as
1 `foo` 2
or call '-->' as simple function with
((-->) 1 2).
So Ruby with this extension would look like.
def Number
# create a point
def @(y)
Point.new(self, y)
end
end
> 1 @ 2
=> #<Point :x=>1, :y=> 2>
> 1.'@'(2) # call using normal 'dot' way.
=> #<Point :x=>1, :y=> 2>
The use of single quote 1.'@'(2) looks consistent with how symbol are
quoted in Ruby -- you can't write :@ but you have to write :'@' to
specify symbol '@'.
This should illiminate the different between operator and method.
It's a little syntactic sugar, but allow better DSL and consistency.