Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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",
like image 831
Chloe Avatar asked Dec 24 '13 03:12

Chloe


People also ask

How do I print all elements in an array in one line?

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.

How do I print an array element in Ruby?

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.

How do you access values in an array in Ruby?

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.


2 Answers

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 };
like image 85
Stoic Avatar answered Sep 28 '22 12:09

Stoic


Try:

> puts Post.all.map(&:inspect).join("\n")
like image 27
vee Avatar answered Sep 28 '22 13:09

vee