From: Daniel Schierbeck Date: 2006-07-28T02:55:05+09:00 Subject: Re: Symbols are your friends Caleb Clausen wrote: > On 7/27/06, Daniel Schierbeck wrote: >> Yes, it's time for another Symbol trick! >> >> class Symbol >> def ===(obj) >> obj.respond_to? "to_#{self}" >> end >> end > > This idea has been discussed on this list before; I can't find the > thread at the moment. > This seems like a really clever idea, and is fine for just playing > around... but it's not advisable for general use. You're changing the > semantics of Symbol#===, which will break things like this: > > case method_name > when :reverse > #.... > when :each > #... > else #..... > end Yes, that's true -- I only ever intended it to be a trick. > (You're prepending "to_" to your method names before checking; I don't > know why. This way seems more general....) I was using it to demonstrate how you could duck type check with a case statement, so focusing on the "type" made sense. I see this all the time: case obj when Integer then foo when String then bar end and it strikes me as not being very duckish (quacky?) Using if statements can be annoying: if obj.respond_to? :to_str foo elsif obj.respond_to? :to_int bar end Maybe this would work? class Symbol def ===(obj) return true if self == obj obj.respond_to? "to_#{self}" end end though something like this may cause trouble: obj = :int case obj when :int then "integer" when :str then "string" end Cheers, Daniel