From: Josh Cheek Date: 2009-10-21T00:01:39+09:00 Subject: Re: recursive function problem --000e0cd1723a6c348804765f225b Content-Type: text/plain; charset=ISO-8859-1 On Tue, Oct 20, 2009 at 9:30 AM, Aurora S.r.l. wrote: > > I don't really know how to read the docs, but this seems like the kind > > of > > thing that I would expect the pp library to do for us. I tried about 15 > > different ways to get it to do this, and only ever got the same as the > > default p function. If pp does address this issue, can someone explain > > how > > to get it to work? > > Bravo!!! > > I come from PHP and my first need was a function similar to print_r() (I > develop with Rails 2 now), so I just started (very lazily :-) ) to write > it... and you are giving me the code, written with a ruby philosophy! > Many thanks!!!!! Anyway, it's less bizarre that a such modern language > doesn't implement in native libraries these prehistorical functions, I > think... > -- > Posted via http://www.ruby-forum.com/. > > Well, if you just need to look at it, inspect usually works. It's just when you get long lists or lots of nesting, using inspect sometimes still isn't enough. I really think that pp should do it, but can't figure out how. If I were doing it, myself, I would monkey patch it into the hash class, something like this: class Hash def readable( tabs_num = -1 ) tabs_num += 1 self.inject(String.new)do | str , ( key , value ) | rhs = value.is_a?(Hash) ? "\n#{value.readable tabs_num}" : "#{value.inspect}\n" str << "#{"\t" * tabs_num}#{key.inspect} => #{rhs}" end end end params = { :abc => 'def' , 3 => {1=>true,2=>{'xyz'=>/xyz/}} , 5 => 5 } puts params.readable But some people here hate monkey patching, so I didn't post that earlier. Also, I found that YAML gives something very similar to what we are doing here, with require 'yaml' puts params.to_yaml --000e0cd1723a6c348804765f225b--