From: Daniel Schierbeck Date: 2006-07-28T05:55:06+09:00 Subject: Re: Symbols are your friends Caleb Clausen wrote: > On 7/27/06, Daniel Schierbeck wrote: >> > (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 > > I see where you're coming from, but I guess I just don't see that > #to_* methods as being that special. Why wouldn't you want to do this > kind of dispatch for other methods too? Because I only think the #to_x methods are directly related to types. They even have more nuances than class-based types; there's a difference between defining #to_s and defining #to_str, for example. > Using the code I posted previously, the above conditionals could be > written as: > > case obj > when -:to_str > foo > when -:to_int > bar > end > > I like that one best. > > Fooling with the existing Symbol#=== in any way is very likely to > break some existing libs which assumes the current definition always > obtains... my way lets you use (almost-)symbols in the way you want to > use them. It is incompatible with libs that also define Symbol#-@ in a > different way, but those are presumably much rarer, perhaps > nonexistant. (Nobody's as crazy as I am.) If you really want this > feature in a general way, (and I do, for Reg) this seems to be the > best compromise. Yes, I've adopted your solution; it is indeed the best way to get around the problem. This isn't something I believe should go into core or anything, I just think it's a great showcase of Ruby's flexibility. Cheers, Daniel