From: Yehuda Katz Date: 2009-06-07T09:19:53+09:00 Subject: [ruby-core:23738] Ducktyping interface --0015175cddd80001e4046bb6fbb4 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Matz, I've been working on adding some specs to RubySpec related to the ducktyping interface. I have observed the following behavior and want to know whether or not it's intentional. Let's use the #to_s coercion as an example: 1. If the object has a method #to_s, it's called. 2. If #to_s returns something that is not a String, a TypeError is raised. In MRI, the mechanism for determining if an object has a method #to_s is to call respond_to?. This means that even if the method does not exist, #to_s will get called, and fall through to #method_missing, if the #respond_to method returns true for :to_s. As a result, when using MRI, it is possible to implement the duck-typing interface without defining #to_s, but instead defining a combination of #respond_to? and #method_missing that returns a String. Is this intentional? Would it be ok for an alternative implementation to look up the #to_s method using an internal check instead of calling the user-defined #respond_to?, as MRI does? In other words, is the only "correct" way to enlist in Ruby coercion to define to_s explicitly, or is another correct way to define respond_to? and method_missing to return an appropriate response? -- Yehuda Katz Developer | Engine Yard (ph) 718.877.1325 --0015175cddd80001e4046bb6fbb4 Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable
Matz,

I've been working on adding some specs t= o RubySpec related to the ducktyping interface. I have observed the followi= ng behavior and want to know whether or not it's intentional. Let's= use the #to_s coercion as an example:

1. If the object has a method #to_s, it's called.
<= div>2. If #to_s returns something that is not a String, a TypeError is rais= ed.=A0

In MRI, the mechanism for determining if an= object has a method #to_s is to call respond_to?. This means that even if = the method does not exist, #to_s will get called, and fall through to #meth= od_missing, if the #respond_to method returns true for :to_s. As a result, = when using MRI, it is possible to implement the duck-typing interface witho= ut defining #to_s, but instead defining a combination of #respond_to? and #= method_missing that returns a String.

Is this intentional? Would it be ok for an alternative = implementation to look up the #to_s method using an internal check instead = of calling the user-defined #respond_to?, as MRI does?=A0

In other words, is the only "correct" way to enlist in Ruby = coercion to define to_s explicitly, or is another correct way to define res= pond_to? and method_missing to return an appropriate response?

--
Yehuda Katz
Developer | Engine Yard
(ph) 718.877.1325
--0015175cddd80001e4046bb6fbb4--