On 3/13/2005, "Sam Roberts" <sroberts / uniserve.com> wrote: >I can give something a #to_str, which should be an indication that it is >duck-type compat to a String (as opposed to #to_s, which converts >something to a String). > >That's all fine, but that doesn't mean that String will allow itself to >be compared to my class: > >irb(main):003:0> class Str; def initialize(s) @s = s; end; def to_str() >@s; end end >=> nil >irb(main):004:0> str = Str.new('hi') >=> #<Str:0x339fbc @s="hi"> >irb(main):005:0> 'hi' == str >=> false >irb(main):006:0> 'hi' == str.to_str >=> true > > >I can add as many methods as I want to String, I can even proxy every >single method in it using #undefined_method (which is as duck-typed as >you can get) but I still don't think a String object will ever "== => >true" to my class. > >Am I right about this? If your class defines #to_str and #<==>, it should work. String#== checks for #to_str, if that's OK, transfers to String#<==> which checks for #to_str, if that's OK, transfers to OtherClass#<==>. Then your #<==> must take a String and compare it returning -1, 0 or 1. Not sure if there's a version requirement; works with 1.8.2, I believe. >Thanks, >Sam E