How can I print each element of an array on its own line in the Rails console?

Chloe picture Chloe · Dec 24, 2013 · Viewed 15k times · Source

When I run the Rails console, how can I display each item on its own line? Instead of

> Post.all
=> #<ActiveRecord::Relation [#<Post id: 1, title: "Post #0", comment: nil, link: "http://yahoo.com", user_id: 1, created_at: "2013-09-30 02:29:28", updated_at: "2013-09-30 02:29:28">, #<Post id: 2, title: "Post #1", comment: nil,...

it would display as

> Post.all
=> #<ActiveRecord::Relation [
#<Post id: 1, title: "Post #0", comment: nil, link: "http://yahoo.com", user_id: 1, created_at: "2013-09-30 02:29:28", updated_at: "2013-09-30 02:29:28">, 
#<Post id: 2, title: "Post #1", comment: nil,...

Similar to x in Perl debugger. I tried

Post.all.each{|e| e.inspect + "\n"}

But that only made it worse, and wasn't very convenient.

I saw Ruby on Rails: pretty print for variable.hash_set.inspect ... is there a way to pretty print .inpsect in the console? and https://github.com/michaeldv/awesome_print

but that doesn't seem to work

irb(main):005:0> require "awesome_print"
=> false
irb(main):006:0> ap Post.all
#<ActiveRecord::Relation [#<Post id: 1, title: "Post #0",

Answer

Stoic picture Stoic · Dec 24, 2013

Try:

Post.all.each {|e| puts e.inspect }

Thing to notice here is that puts function automatically adds a newline character after the statement, and if you instead use print it will function in a similar manner as puts without the newline character at the end.


If you are using awesome_print, try:

ap Post.all.to_a

Further, when you issue the first command, the output will be repeated at the end (as per your comment) to show the output of the current expression. You can suppress it by appending a ; (semi-colon) at the end of the command, like this:

Post.all.each { |e| puts e.inspect };