4

Can I limit the recursion depth of PP.pp or to_yaml in Ruby? If not is there another function I can use?

LittleBobbyTables - Au Revoir
  • 32,008
  • 25
  • 109
  • 114
rhlee
  • 3,857
  • 5
  • 33
  • 38
  • The recursion depth is already clamped to 0. Did you mean that you want to keep recursing for a while, printing redundant data? `h1={}; h2={a:h1}; h1[:b]=h2; pp h1 #=> "{:b=>{:a=>{...}}}"` and then `p h1.to_yaml #=> "--- &id001 \n:b: \n :a: *id001\n"` – Phrogz Jan 05 '11 at 16:20
  • 1
    I think he means that no matter how deeply nested the (distinct) objects are in something he's trying to `pp`, there should be a limit that prevents it form traversing too deeply. So that `[[[[[[[1]]]]]]]` should only go 3 or 4 arrays deep before indicating that the deeper levels are omitted for the sake of brevity. – Ken Bloom Jan 05 '11 at 18:49
  • Inspect kinda does what I want in that it only goes down one level. I just need it inspect to split over multiple lines rather than just a single line. – rhlee Jan 07 '11 at 10:42

1 Answers1

0

As far as I know there is no easy way to do this. The #inspect method which almost every Ruby object implements cannot be limited by depth.

You would have to implement that by yourself, for example you could build a recursive method that takes the an object and an Integer value to represent the current depth. The main problem is, that you need to handle output for objects of each expected class differently to simulate their specific #inspect output, as you can't use their original #inspect method.

aef
  • 4,498
  • 7
  • 26
  • 44