From: ES Date: 2005-03-14T04:48:41+09:00 Subject: Re: how do you duck-type something to String, so String believes you? On 3/13/2005, "Navindra Umanee" wrote: >> What you can do is override String.== to take this into consideration. >> >> class String >> alias :_equals :== >> def ==(o) >> _equals(o.to_s) >> end >> end > >ES is right, you don't need to redefine == in String if you do it in >Str. I didn't notice that str1 and str2 were swapped around in the >call to rb_equal. > > if (TYPE(str2) != T_STRING) { > if (!rb_respond_to(str2, rb_intern("to_str"))) { > return Qfalse; > } > return rb_equal(str2, str1); > } > >Clever. :-) Possibly a bit too clever. While I like the reversal of roles in this fashion to facilitate the current implementation, I'm somewhat leery of the concept. First of all, an *single* explicit method is used, not the representative API of the class; for example in this instance, anything that defines #to_s could be considered to be valid input; sometimes more matching methods might be required. It is considerably harder to construct the idiom this way, so I can see the need for this compromise. Secondly, the naming is confusing. #to_str? str is not a class and a very similar name #to_s does something different. A better choice would use the entire class name (lowercase would be fine) and clearly indicate that it's not necessarily being made into another class but used as an instance of the other class; hence SomeClass#as_string or something similar like my favourite SomeClass#quack_like_a_string. I think this is being changed somehow in 2.0, even if it's just better integration and clearer guidelines for usage. >Cheers, >Navin. E