Stop rails console from printing out the object at the end of a loop

Ruby on-RailsRubyConsoleIrb

Ruby on-Rails Problem Overview


If I, say, loop through all the instances of a given model and output something from each, at the end, irb will still print the entire object.

If the object ends up taking hundreds of lines, it'll be a long way up before I see what I was actually looking for. Is there a way to disable this in the rails console?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

Solution 2 - Ruby on-Rails

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

Solution 3 - Ruby on-Rails

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

Solution 4 - Ruby on-Rails

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondsp_099View Question on Stackoverflow
Solution 1 - Ruby on-RailsaefView Answer on Stackoverflow
Solution 2 - Ruby on-RailslulalalaView Answer on Stackoverflow
Solution 3 - Ruby on-RailsRajaRaviVarmaView Answer on Stackoverflow
Solution 4 - Ruby on-RailsstevecView Answer on Stackoverflow