Daniel Berger
6/2/2009 1:35:00 AM
> -----Original Message-----
> From: p.witty@gmail.com [mailto:p.witty@gmail.com]
> Sent: Monday, June 01, 2009 7:06 PM
> To: ruby-talk ML
> Subject: Ruby enhancement suggestion
>
> I'm fairly certain this isn't the proper place to suggestion minor
> improvements/extensions to the ruby language, but this is something I
> constantly find myself wishing was available:
>
> # Extension to ruby class Hash
> class Hash
> def join(key_value_sep="=>", pair_sep=",")
> result = ""
> self.each { |k,v| result << k.to_s << key_value_sep << v.to_s <<
> pair_sep }
> result.chomp pair_sep
> end
> end
>
> I'm sure there's an even cleaner way to do this (and I'd love to see
> it!!), but the point is so that I can do something like this:
>
> >> hash = {}
> => {}
> >> (0..20).each {|i| hash[i] = i+1 }
> => 0..20
> >> hash.join
> =>
> "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"
> >> hash.join " maps to ", ", "
> => "16 maps to 17, 5 maps to 6, 11 maps to 12, 0 maps to 1, 17 maps to
> 18, 6 maps to 7, 12 maps to 13, 1 maps to 2, 18 maps to 19, 7 maps to
> 8,
> 13 maps to 14, 2 maps to 3, 19 maps to 20, 8 maps to 9, 14 maps to 15,
> 3
> maps to 4, 20 maps to 21, 9 maps to 10, 15 maps to 16, 4 maps to 5, 10
> maps to 11"
>
>
> Is there currently some easy, builtin way to get this sort of output
> that I'm simply unaware of??
Pretty print might suit your needs.
require 'pp'
pp hash
Regards,
Dan