Ruby's Approach: How To Coerce?

A

allan.m.miller

I'm relatively new to Ruby, and trying to understand Ruby's type
coercion mechanism.

More specifically, assuming one is writing a + operator, would it be
more correct "idiomatically" in Ruby to:

(1) Check for a specific type (e.g., using object.class ==) in the
implementation of def +(arg), and raise an exception if an unsupported
arg type is passed (this seems incorrect for Ruby, more suitable for a
statically typed language).

(2) Assume that if the object arg doesn't implement/respond to coerce,
then it is incapable of being "added" (this seems more correct).

(3) In the implementation of coerce in the arg's class, either check
object.class and implement the specific coercion based on the class of
arg, raise an exception otherwise.

I don't see how to get around (3) - if you leave it at (2) all you know
is that the arg can be "coerced" - but the question remains - can it be
coerced in a meaningful way to the class of the receiver object?

Thanks.
 
R

Robert Klemme

I'm relatively new to Ruby, and trying to understand Ruby's type
coercion mechanism.

More specifically, assuming one is writing a + operator, would it be
more correct "idiomatically" in Ruby to:

(1) Check for a specific type (e.g., using object.class ==) in the
implementation of def +(arg), and raise an exception if an unsupported
arg type is passed (this seems incorrect for Ruby, more suitable for a
statically typed language).

IMHO you should try to coerce the arg if you cannot add it directly or
add it after some conversion. I'm not 100% sure about the last bit but
coercion should be done.
(2) Assume that if the object arg doesn't implement/respond to coerce,
then it is incapable of being "added" (this seems more correct).

(3) In the implementation of coerce in the arg's class, either check
object.class and implement the specific coercion based on the class of
arg, raise an exception otherwise.

You should definitively do that.
I don't see how to get around (3) - if you leave it at (2) all you know
is that the arg can be "coerced" - but the question remains - can it be
coerced in a meaningful way to the class of the receiver object?

Thanks.

Does this help:

http://www.rubygarden.org/ruby?CoerceExplanation

Kind regards

robert
 

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

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,078
Latest member
MakersCBDBlood

Latest Threads

Top