From: Jean-Hugues ROBERT Date: 2004-04-30T04:30:09+09:00 Subject: Re: coerce(), what protocol to implement it At 03:45 30/04/2004 +0900, you wrote: >Hi, > >I need to write a class whose instances can be on the left side of Sorry, I meant on the right side. 38 and still I can figure it out ;-) >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 > > >------------------------------------------------------------------------- >Web: http://hdl.handle.net/1030.37/1.1 >Phone: +33 (0) 4 92 27 74 17 ------------------------------------------------------------------------- Web: http://hdl.handle.net/1030.37/1.1 Phone: +33 (0) 4 92 27 74 17