On Fri, 25 Jan 2013 23:52:51 +0100, Nokan Emiro <uzleepito / gmail.com> wrote:

> Hi,
>
> Is there any way to somehow redefine operations like '&&' between my
> objects?
> '&&' is not defined as a method so I can't just overload it.  (Ruby does
> not care
> if an object responds to :&&, it is simply not used.)  Operators with
> higher precedence
> than '&&' usually work fine -- except '[]='.  Seems like above '&&' it is
> the object's
> responsibility to do operations and below that line it is the language
> itself that
> enforces the rules.  But is there a way to define custom code what should
> de done by
> an expression like 'x && y'?
>
> The same limitation bothers me with '||', and with 'and', 'or' and 'not'.
> (Yes, I know that they are not operators but designed to be flow control
> keywords,
> however they are often used as operators...)

Since I think Ruby 1.9 you can redefine the unary `!` operator (class A; def !; true; end end). This will also change the behavior of `not`.

`||` and `&&` are part of the language and you can't redefine them. (These short-circuit, which would be impossible to do if they were redefined.) They're handled separately throughout the parser.


> At the same time I'm struggling with the []=.  The strange thing with this
> is
> that the return value of the []= method is abandoned by Ruby but I expected
> it to be the value of the expression that the []= method returns:
> [...]
> Is this a
> deliberate behaviour or
> just nobody cares the value of it?

This is intended, to make assignments sane. The same applies to every method with name ending with '='. This is intended to make code like `a[0] = b[0] = c` or `a[0], b[0] = c, d` behave according to coders' expectations.


-- 
Matma Rex