From: Rob Biedenharn Date: 2009-06-02T11:29:14+09:00 Subject: Re: Ruby enhancement suggestion On Jun 1, 2009, at 10:01 PM, Steve Hull wrote: > Joel VanderWerf wrote: >> p h.map{|pair| pair.join("=>")}.join(",") > > That is indeed nice and compact. Thanks Joel!! That'll do quite > nicely > for my needs. :) > > Daniel Berger wrote: >> require 'pp' >> pp hash > > Thanks Dan! That's a cool feature, but not really what I'm looking > for > in the hash.join idea. It is indeed something I'll be using in the > future though. :) > -- Before the other replies, I was thinking that you just wanted Hash#inspect irb> hash = {} => {} irb> (0..20).each {|i| hash[i] = i+1 } => 0..20 irb> hash => {16=>17, 5=>6, 11=>12, 0=>1, 17=>18, 6=>7, 12=>13, 1=>2, 18=>19, 7=>8, 13=>14, 2=>3, 19=>20, 8=>9, 14=>15, 3=>4, 20=>21, 9=>10, 15=>16, 4=>5, 10=>11} irb> puts hash.inspect {16=>17, 5=>6, 11=>12, 0=>1, 17=>18, 6=>7, 12=>13, 1=>2, 18=>19, 7=>8, 13=>14, 2=>3, 19=>20, 8=>9, 14=>15, 3=>4, 20=>21, 9=>10, 15=>16, 4=>5, 10=>11} => nil irb> hash.inspect => "{16=>17, 5=>6, 11=>12, 0=>1, 17=>18, 6=>7, 12=>13, 1=>2, 18=>19, 7=>8, 13=>14, 2=>3, 19=>20, 8=>9, 14=>15, 3=>4, 20=>21, 9=>10, 15=>16, 4=>5, 10=>11}" It even keeps the type of the key straight for you. irb> {:sym => "I'm a symbol", 'string' => "String here!", 1 => 'Fixnum, too'}.inspect => "{1=>\"Fixnum, too\", :sym=>\"I'm a symbol\", \"string\"=>\"String here!\"}" Of course, you could manage that yourself, too, easily enough with something close to what Joel said: irb> class Hash irb> def join(key_value_sep="=>", pair_sep=",") irb> map{|k,v| [k.inspect,v.inspect].join(key_value_sep)}.join(pair_sep) irb> end irb> end => nil irb> puts hash.join(" says ", ",\n ") 16 says 17, 5 says 6, 11 says 12, 0 says 1, 17 says 18, 6 says 7, 12 says 13, 1 says 2, 18 says 19, 7 says 8, 13 says 14, 2 says 3, 19 says 20, 8 says 9, 14 says 15, 3 says 4, 20 says 21, 9 says 10, 15 says 16, 4 says 5, 10 says 11 => nil Note that #inspect is "smarter" because the individual keys and values can do what is right for them. Try the simple #join varieties with values that are themselves Hashes or Arrays. -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com