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