From: Brian Candler Date: 2009-01-05T21:35:58+09:00 Subject: Re: VERY simple question about "?" Tom Cloyd wrote: > OK, let's assume we have the language problem solved (ha! - not likely > to happen). Nann-methods == "non-alphabetically-named methods". That's not exactly the same though. You can (with a bit of work) define arbitrary methods with non-alphanumeric names, but they are not operators. The things we're talking about are called "operators" because they look, syntactically, like operators in other languages, and are parsed as such. foo + bar # infix binary plus (method +) - foo # prefix unary minus (method -@) That is: "arg1 op arg2" instead of "arg1.methodname(arg2)" The fundamental thing is that the infix/prefix notation shown above is parsed successfully, but then translated into normal method calls. You can then define or redefine these methods, just like any other methods. class Foo def -@ "minus #{self}" end end f = Foo.new p -f # operator notation (unary minus) p f.-@ # same but using explicit method call > The core > problem still remains - what the blazes does that THING > do/mean/produce...??? It produces whatever it is defined to produce :-) That is, class Foo may or may not implement the unary minus operator/method (or any other operator). If it does, it is the programmer's choice as to what it does. Equally, I could define a method Foo#xcikuhruh. It would be my choice what it does :-) You may have an implicit expectation of, say, what the "*" operator does, i.e. multiplication. But it may not make sense in non-numeric contexts. For example, the facets library defines a way to combine Proc objects using *: ----------------------------------------------------------------- Proc#* *(x) ------------------------------------------------------------------------ Operator for Proc#compose and Integer#times_collect/of. a = lambda { |x| x + 4 } b = lambda { |y| y / 2 } (a * b).call(4) #=> 6 (b * a).call(4) #=> 4 CREDIT: Dave An operator precedence table shows all the operators known by Ruby, and the ways they interact with each other in complex expressions. It doesn't make sense to include what they "mean", because they will mean different things when applied to different objects. And the joy is, you can make them mean whatever you like when applied to *your* objects. A neat trick I've seen is a pathname class which uses the '/' operator to compose paths: e.g. path1 = MyPath.new("home") path2 = path1 / "bar" / "baz" # results in /home/bar/baz Saying that the '/' operator means "division" doesn't make sense here. HTH, Brian. -- Posted via http://www.ruby-forum.com/.