Monday, May 23, 2005

print_r for Ruby

print_r is a function that PHP developers like to use to display the contents of an object. Here's a version I wrote for Ruby:

def print_r(hash, level=0)
result = " "*level + "{\n"
hash.keys.each do |key|
result += " "*(level+1) + "#{key} => "
if hash[key].instance_of? Hash
result += "\n" + print_r(hash[key], level+2)
else
result += "#{hash[key]}\n"
end
end
result += " "*level + "}\n"
end

It pretty-prints the contents of a nested map; for example, print_r({"A"=>1, "B"=>{"a"=>"@", "s"=>"$"}, "C"=>3}) displays the following:

{
A => 1
B =>
{
a => @
s => $
}
C => 3
}

2 Comments:

At 5/23/2005 10:49 p.m., Anonymous Anonymous said...

why not override inspect, instead of creating a new method name

 
At 5/23/2005 10:51 p.m., Blogger Jonathan said...

Hi Anonymous - The person I wrote this for wanted some formatting, as inspect was giving him a huge amount of data.

Anyway it turns out that he wanted to use it on Objects in general, not just nested maps. So the final solution was to use #inspect, and replace commas with newlines.

 

Post a Comment

<< Home