Robert A Henru Robert A Henru - 11 days ago 8
Ruby Question

Can I repeat command in irb?

Is there an easy way to repeat a previous command in Ruby irb?
I wish to have something like using exclamation mark (!) in Unix.

Thank you.

Answer
def repeat_last_irb
  eval(IRB.CurrentContext.io.line(-2))
end

then you can use replat_last_irb in you irb console to run last input.

IRB.CurrentContext.io is like this below:

ruby-1.9.3-p0 :001 > def hello
ruby-1.9.3-p0 :002?>   end
 => nil 
ruby-1.9.3-p0 :003 > IRB.CurrentContext.io
 => #<IRB::ReadlineInputMethod:0x00000001c7b860 @file_name="(line)", @line_no=3, @line=[nil, "def hello\n", "end\n", "IRB.CurrentContext.io\n"], @eof=false, @stdin=#<IO:fd 0>, @stdout=#<IO:fd 1>, @prompt="ruby-1.9.3-p0 :003 > "> 

this Object save irb all io info, and with a line method to get every line you input.

so, we can use eval to repeat last input.