Symbols aren't strings. They aren't even immutable strings. They are symbols. They are also very good keys for hashes, assuming the code building the hash thought so also. It is often the case, however, that hashes received by your code may be keyed by either strings or symbols, or a mixture thereof, and you'd like to be able to handle either case simply and elegantly. The simplest thing to do is to call #extend on the offending hash with the following module:
module SymbolicKeyHash def (key) case key when Symbol include?(key) ? super(key) : super(key.to_s) when String include?(key) ? super(key) : super(key.to_sym) else super(key) end end end
That's good as far as it goes, but it really isn't nice to mess with the interface of an argument you've been passed. Instead, we rely on a Proxy to wrap it:
def bar(hash) hash = Proxy.new(hash) hash.extend SymbolicKeyHash do_something(hash[:first_thing], hash[:second_thing]) endEnjoy!