J
Jean-Hugues ROBERT
Hi,
I need to write a class whose instances can be on the left side of
a + operator. I am ready to implement whatever make the other side
happy. But what is that I need to implement ?
I am trying to understand coerce()
Apparently when a receiver is not happy with the type of a parameter,
it invokes coerce() on the parameter.
if not_happy_with? param then x = param.coerce( self)
coerce() then returns an array of two items. Both items can be new
objects. However coerce() says that they are "compatible".
Question:
1) What happens if coerce() cannot produce such a result when there
are no such "compatible" objects ? Apparently coerce() raises an
ArgumentError exception. Right ?
2) How can I make MyClass instances coercible ? That must be possible,
because 1.coerce( "2") works, yet "2".coerce( 1) does not...
3) Why does 1.coerce( "3") returns [3.0,1.0] instead of [1,3] while
1.coerce( 3) returns [1,3] ?
4) Can I redefine coerce() ? If so, when is it called ? (I tried,
it is not called...)
5) By defining to_str() I can have "xx" + MyClass.new(xx) work. What
do I have to redefine to have 1 + MyClass.new(xx) work ?
Google "ruby coerce" provided little help.
Thanks in advance,
Yours,
Jean-Hugues
I need to write a class whose instances can be on the left side of
a + operator. I am ready to implement whatever make the other side
happy. But what is that I need to implement ?
I am trying to understand coerce()
Apparently when a receiver is not happy with the type of a parameter,
it invokes coerce() on the parameter.
if not_happy_with? param then x = param.coerce( self)
coerce() then returns an array of two items. Both items can be new
objects. However coerce() says that they are "compatible".
Question:
1) What happens if coerce() cannot produce such a result when there
are no such "compatible" objects ? Apparently coerce() raises an
ArgumentError exception. Right ?
2) How can I make MyClass instances coercible ? That must be possible,
because 1.coerce( "2") works, yet "2".coerce( 1) does not...
3) Why does 1.coerce( "3") returns [3.0,1.0] instead of [1,3] while
1.coerce( 3) returns [1,3] ?
4) Can I redefine coerce() ? If so, when is it called ? (I tried,
it is not called...)
5) By defining to_str() I can have "xx" + MyClass.new(xx) work. What
do I have to redefine to have 1 + MyClass.new(xx) work ?
Google "ruby coerce" provided little help.
Thanks in advance,
Yours,
Jean-Hugues