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…)
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:
class X
def []=(key, value)
“I want to be the value!!”
end
end
x = X.new
x[123] = 456 #=> 456
The value of the last expression is 456, and not the string. I’d like
to
get back the whole
x object instead of the right hand side value here. Yes, I know that
the
value of assignments
is the rhs value, but assignments in general are out of the scope of an
object, while []=
is an exceptional one. It is done by the object itself, so it would be
logical to give the
power to the object to decide the value of the operation. Is this a
deliberate behaviour or
just nobody cares the value of it?