Tolerating ruby hashes and converting strings to symbols

I feel like I always have some sort of issues with hashes in ruby where I don’t access the hash key correctly :roll_eyes:. Rails has a nice feature called HashWithIndifferentAccess to prevent this confusion, but if you are dealing with plain ruby we won’t have this feature. I’ve found the Ruby String .to_sym helpful for converting a string to a symbol in case your hash key requires it.

h = {}
key = "foo"
h[:foo] = "bar"

puts "VALUE: #{h[key]}"
puts "VALUE: #{h[key.to_sym]}"

output:

VALUE: 
VALUE: bar

You can also convert a symbol to a string with .to_s if you need to go that direction.