Sunday, April 5, 2009

Nice output for Ruby objects

Ruby has a wide range of methods to format the output of an object.

Like

1) Inspect
2) y or to_yaml
3) PrettyPrint

y is actually used as a shorthand for to_yaml

example
 
a={'1'=>'one','2'=>'two','3'=>'three','4'=>'four'}

y a

puts a.to_yaml

generates the same output.

Below are the ouputs using different output methods

> Using normal puts
 
usage: puts a

output:

1one2two3three4four

Using y or to_yaml

usage: y a or puts a.to_yaml

output:

"1": one
"2": two
"3": three
"4": four

> Using PrettyPrint

usage: Please do a require 'pp' in your script file,
 
pp a

output:

{"1"=>"one", "2"=>"two", "3"=>"three", "4"=>"four"}

> Using inspect
 
usage: puts a.inspect

output:

{"1"=>"one", "2"=>"two", "3"=>"three", "4"=>"four"}

No comments: