Question about #coerce

J

Jim Cain

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.
 
Y

Yukihiro Matsumoto

Hi,

In message "Question about #coerce"

|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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top