1

When I have a list of hashes, like the result of an .attributes call, what is a short way to create a line-by-line nicely readable output? Like a shortcut for

u.attributes.each {|p| puts p[0].to_s + ": " + p[1].to_s}
Yo Ludke
  • 2,149
  • 2
  • 23
  • 38
  • 1
    I like to use `y hash` or `puts YAML.dump(hash)` that shows your hash in yaml. – oldergod Dec 10 '12 at 08:37
  • 1
    You might like [`awesome_print`](https://github.com/michaeldv/awesome_print). See also [this SO thread](http://stackoverflow.com/questions/8842546/best-way-to-pretty-print-a-hash). – Chris Salzberg Dec 10 '12 at 08:38
  • I recommend `awesome_print` as well. – Haris Krajina Dec 10 '12 at 15:28
  • @oldergod I like your answer most, because it is just intended for a quick rails console inspection of what is there, and don't want to add a gem just for this. And `y` really is a nice way to achieve this, and as short as it can be :) I would mark it as the correct one if you want to post this as an answer – Yo Ludke Dec 11 '12 at 16:41

4 Answers4

2

I'm not sure you can make it much shorter unless you create your own method.

A minor enhancement would be:

u.attributes.each {|k,v| puts "#{k}: #{v}"}

Or you can create an extension to Hash:

class Hash
  def nice_print
    each {|k,v| puts "#{k}: #{v}"}
  end
end

u.attributes.nice_print
Sean Hill
  • 14,978
  • 2
  • 50
  • 56
1

If you are looking for an output for development purposes (in Rails log files for instance), inspect or pretty_inspect should do it :

u.attributes.inspect

or

u.attributes.pretty_inspect

But if what you are looking for is a way to print nicely in Rails console, I believe you will have to write your own method, or use a gem like awesome_print, see : Ruby on Rails: pretty print for variable.hash_set.inspect ... is there a way to pretty print .inpsect in the console?

Community
  • 1
  • 1
Raf
  • 1,083
  • 11
  • 15
1

awesome_print is the way to go

gem install awesome_print

require "ap"
ap u.attributes
doesterr
  • 3,955
  • 19
  • 26
1

AS said in my comments, I like to use y hash or puts YAML.dump(hash) that shows your hash in yaml. It can be used for other objects too.

h = {:a => 1, :b => 2, :c => 3}
# => {:a=>1, :b=>2, :c=>3}
y h
#---
#:a: 1
#:b: 2
#:c: 3
# => nil 

There is also an informative answer about it.

Community
  • 1
  • 1
oldergod
  • 15,033
  • 7
  • 62
  • 88