From: Jeremy Bopp Date: 2012-06-21T12:02:37+09:00 Subject: Re: Symbols and Strings... On 06/20/2012 05:43 PM, Robert Klemme wrote: > On Thu, Jun 21, 2012 at 12:25 AM, Hal Fulton wrote: >> >> On Wed, Jun 20, 2012 at 5:06 PM, Jeremy Bopp wrote: >>> >>> So then, in what cases would it be helpful to use them interchangeably? >>> Is it possible to define a common, useful interface that both Symbol >>> and String could implement. If so, perhaps a class or module could be >>> defined for that interface and incorporated into both classes as >>> appropriate. >>> >>> From what I've seen, the most frequently voiced desire is to be able to >>> use apparently equivalent symbols and strings as fully equivalent hash >>> keys. > > Even that would not be solved by inheritance because instance of > different classes can never be equivalent. I didn't mean to imply that it would. Personally, I prefer having Hash be picky about these things. That generality allows it to be used as the basis for something like HashWithIndifferentAccess without much fuss. Doing things the other way around would be much more difficult. To be honest, the best way to handle this particular issue would probably be to add some syntactic sugar that makes it as easy to instantiate HashWithIndifferentAccess as it is to instantiate Hash. Assuming HashWithIndifferentAccess is available, maybe something like this: def h(regular_hash) HashWithIndifferentAccess.new(regular_hash) end hash = h :a => 1, 'b' => 2 puts hash['a'] #=> 1 puts hash[:b] #=> 2 > PS: I said "If at all..." - so I am not a fan of String as subclass of > Symbol either. To me, Symbol and String really are very different things. Symbol effectively *has* a frozen String instance associated with it but is not itself the String instance. The String#to_sym method is just a convenience method to perform a reverse lookup on such associations, creating them if they don't already exist. In other words, there is an implicit hash that maps Symbol instances to String instances (a... ahem... symbol table). Saying that Symbol and String should have some sort of direct ancestral class relationship with one another based on that fact alone is like saying that the keys and values in your own hashes should always have such a relationship as well. Clearly, or perhaps not so clearly, that's nonsense. :-) -Jeremy