On Feb 11, 2008 8:32 PM, J. Cooper <nefigah / gmail.com> wrote: > I ran into something I hadn't realized (common occurrence). Keying a > hash with a symbol is not the same as using a string. I guess it makes > sense, but I've seen it done both ways, and I had been always using > symbols for my keys. But then I ran into an issue on loading an external > YAML object into a hash, and didn't realize it was keyed with strings so > I got errors the first time around. > > So two questions: > 1) What is the preferred method of keying hashes? Symbols, strings, > other? ----------------- 8< ----------------- Symbols, look at this code Symbol.send( :define_method, :to_proc ){ lambda{|x| x.send self } } unless RUBY_VERSION === /^1\.9/ string_keys = %w{a b c} symbol_keys = string_keys.map(&:to_sym) string_hash = Hash[ *string_keys.zip([42]*3).to_a.flatten ] symbol_hash = Hash[ *symbol_keys.zip([42]*3).to_a.flatten ] p [:symbol, symbol_hash] p [:string, string_hash] puts "So far everything looks fine" string_hash.each_pair do |k,v| k << "..." end ------------------------ 8< ---------------------- Ruby does a fine job by freezing keys of hashes, but I prefer to use immutable objects as keys whenever it is possible for that very reason, in our case that favors Symbols > 2) Is there a smooth way to handle hashes that may have been keyed in > either fashion? Handle them? If I pretended to be even more stupid than I actually believe to be I would say yes sure a_hash.clear ;) But I guess that you want to change from one to the other, let me show you from String to Symbol ------------------------ 8< ---------------------- ### Do not do this at home :) Array.send :define_method, :each_with_index do count = 0 inject([]){|iwi,e| count+=1; iwi << [e,count=count+1]} end unless RUBY_VERSION === /^1\.9/ string_hash = %w{A Brave New World}.each_with_index.inject({}){|h,(v,i)| h.update v => i } p string_hash symbol_hash = Hash[ *string_hash.to_a.map{|k,v|[k.to_sym,v]}.flatten ] p symbol_hash ------------------------ 8< ---------------------- HTH Robert > > Thanks > -- > Posted via http://www.ruby-forum.com/. > > -- http://ruby-smalltalk.blogspot.com/ --- Whereof one cannot speak, thereof one must be silent. Ludwig Wittgenstein