Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I repeat command in irb?

Tags:

ruby

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.

like image 238
Robert A Henru Avatar asked Jun 01 '12 10:06

Robert A Henru


People also ask

How do you run a command in IRB?

To invoke it, type irb at a shell or command prompt, and begin entering Ruby statements and expressions. Use exit or quit to exit irb. Sr.No. Suppress reading of the file ~/.

What is displayed following the => symbol when a command is entered in IRB?

The => symbol lets you know that this is the return value from the Ruby expression. To exit IRB, type exit at the prompt, or press CTRL+D . You'll return to your shell prompt. Let's dig a little deeper into IRB by looking at how you can use it to explore code.

Is there a Ruby REPL?

IRB is the built-in Ruby REPL that every Ruby developer is familiar with. It doesn't have many features, but it does what it's supposed to. You type in code & you get the results back.

How do I load a Ruby file in IRB?

From the main menu, choose Tools | Load file/selection into IRB/Rails console.


2 Answers

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.

like image 189
Hooopo Avatar answered Nov 15 '22 11:11

Hooopo


Up arrow gets you history line by line. Pry has more goodies but I haven't tried it yet.

like image 20
seph Avatar answered Nov 15 '22 10:11

seph