This is my understanding of the customary use of coerce: it is a request
to convert the receiver into the same type as the argument:
x.coerce(y)
is asking x to return a copy of itself that is the same class as y. I
understand that the return value is an array: [y1, x1].
What if x cannot be represented in the same class as y, but both could
be represented in a third class? Is it acceptable to return [y1, x1]
such that both objects have been rendered in a third class?
What if nothing can be done? Is it customary to raise an exception, or
return something like [y, nil]?
I’m working on implementing #coerce in my Oracle library, and I want to
make sure I do it the Ruby Way as much as possible.
Hi,
What if x cannot be represented in the same class as y, but both could
be represented in a third class? Is it acceptable to return [y1, x1]
such that both objects have been rendered in a third class?
Acceptable. It’s only reason to return converted y1 and x1 from
coerce, although no known class does that yet.
What if nothing can be done? Is it customary to raise an exception, or
return something like [y, nil]?
Raise TypeError exception.
matz.
···
In message “Question about #coerce” on 03/07/09, Jim Cain list@jimcain.us writes:
Jim Cain wrote:
This is my understanding of the customary use of coerce…
I think Matz has already answered your main questions; I just wanted to
point out this additional resource on the RubyGarden Wiki:
http://www.rubygarden.org/ruby?CoerceExplanation
For others who may not yet understand the purpose of #coerce, this
explanation by Chris Pine should prove extremely beneficial.
Hope this helps,
Lyle