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",
Print Array in One Line with Java StreamsArrays. toString() and Arrays. toDeepString() just print the contents in a fixed manner and were added as convenience methods that remove the need for you to create a manual for loop.
Ruby printing array contentsThe array as a parameter to the puts or print method is the simplest way to print the contents of the array. Each element is printed on a separate line. Using the inspect method, the output is more readable. The line prints the string representation of the array to the terminal.
The at() method of an array in Ruby is used to access elements of an array. It accepts an integer value and returns the element.
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 };
Try:
> puts Post.all.map(&:inspect).join("\n")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With