当我运行 Rails 控制台时,如何在单独的行中显示每个项目?而不是
> 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,...
它会显示为
> 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,...
类似于 Perl 调试器中的 x
。我试过了
Post.all.each{|e| e.inspect + "\n"}
但这只会让事情变得更糟,而且不是很方便。
我看到了Ruby on Rails: pretty print for variable.hash_set.inspect ... is there a way to pretty print .inpsect in the console?和 https://github.com/michaeldv/awesome_print
但这似乎行不通
irb(main):005:0> require "awesome_print"
=> false
irb(main):006:0> ap Post.all
#<ActiveRecord::Relation [#<Post id: 1, title: "Post #0",
最佳答案
尝试:
Post.all.each {|e| puts e.inspect }
这里要注意的是 puts
函数会在语句后自动添加一个换行符,如果您改为使用 print
,它将以与 类似的方式运行>puts
最后没有换行符。
如果您正在使用 awesome_print,请尝试:
ap Post.all.to_a
此外,当您发出第一个命令时,输出将在末尾重复(根据您的评论)以显示当前表达式的输出。您可以通过在命令末尾附加 ;(分号)来抑制它,如下所示:
Post.all.each { |e| puts e.inspect };
关于ruby-on-rails - 如何在 Rails 控制台中将数组的每个元素打印在各自的行中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20754352/