10

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",
Community
  • 1
  • 1
Chloe
  • 25,162
  • 40
  • 190
  • 357
  • Note that ```Post.all``` doesn't return an array, but an ```ActiveRecord::Relation```. For a real ```Array``` you need ```#to_a```. – paradoja Dec 24 '13 at 03:15

2 Answers2

18

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 };
Stoic
  • 10,536
  • 6
  • 41
  • 60
  • This works, but it repeats itself at the end without newlines all all one line. This is what it looks like: http://pastie.org/private/zy88frmnslbtpkvfowupxq – Chloe Dec 24 '13 at 03:27
  • Thanks, `ap Post.all.to_a` worked! With colors no less! – Chloe Dec 24 '13 at 03:30
  • 3
    The semicolon trick doesn't seem to work with Rails 4. It just seems to ignore the whole statement. But this works: `Post.all.each { |e| puts e.inspect };1` which prints a 1 at the end. – Chloe Dec 24 '13 at 03:39
  • @Chloe: should work. The `semi-colon` will suppress the output of the whole expression/command. So, if your command explicitly prints something it will be printed even with the ;. Try running: `puts "help"` vs `puts "help";` in your console. – Stoic Dec 24 '13 at 03:41
9

Try:

> puts Post.all.map(&:inspect).join("\n")
vee
  • 38,255
  • 7
  • 74
  • 78