停止 Rails 控制台在循环结束时打印出对象

比方说,如果我循环遍历给定模型的所有实例并从每个实例中输出一些内容,最后,irb 仍然会打印整个对象。

如果这个物体最终有几百条直线,那么在我看到我真正要找的东西之前,它还有很长的路要走。有办法在 Rails 控制台中禁用它吗?

32308 次浏览

Call conf.echo = false and it will not print the return value. This works for any irb session, not just Rails console.

In case you want to make it permanent, add it to your irb config.

echo 'IRB.conf[:ECHO] = false' >> $HOME/.irbrc

If you don't want to disable the echo in general you could also call multiple expressions in one command line. Only the last expression's output will be displayed.

big_result(input); 0

To temporarily stop the console from printing the return values you can issue a nil statement at the end of your loop or function, but before pressing the return.

record.each do |r|
puts r.properties
end; nil

Or it can be a number too, if you want to reduce typing. But it can be confusing in scenarios, which I can't think of.

record.each do |r|
puts r.properties
end; 0

This frustrated me a lot, because I was using pry-rails gem, some solutions wouldn't work for me.

So here's what worked in 2 steps:

  1. Simply adding ; to the end of the very last command will be enough to silence the output from printing.
  2. It may still print the sql that was executed. So to silence that, surround it with
ActiveRecord::Base.logger.silence do
# code here
end

Example

If you want to run this

User.all do |user|
puts user.first_name
end

then this will ensure nothing else prints to screen:

ActiveRecord::Base.logger.silence do
User.all do |user|
puts user.first_name
end
end;

(don't forget the ; at the very end)