Can i repeat the command in irb?

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

Thank.

+5
source share
8 answers
def repeat_last_irb
  eval(IRB.CurrentContext.io.line(-2))
end

then you can use replat_last_irbirb in the console to run the last input.

IRB.CurrentContext.io is as follows:

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 will save irb all io info and using the line method to get each input line.

so we can use eval to repeat the last input.

+11
source

An up arrow takes you in turns. Pry has more goodies, but I haven't tried it yet.

+7
source

, Pry REPL ( ) play -i:

. :

[31] (pry) main: 0> (1..5).map do |v|
[31] (pry) main: 0*   v * 2
[31] (pry) main: 0* end  
=> [2, 4, 6, 8, 10]
[32] (pry) main: 0> play -i 31
=> [2, 4, 6, 8, 10]
[33] (pry) main: 0> 

play -i ( [] ) , .

play . wiki ,

, , hist, hist --replay :

[37] (pry) main: 0> puts "hello world"
hello world
=> nil
[38] (pry) main: 0> hist --tail
9699: _file_
9700: (1..10).map do |v|
9701: (1..5).map do |v|
9702:   v * 2
9703: end
9704: play -i 31
9705: _
9706: hist --tail
9707: hist -r
9708: puts "hello world"
[39] (pry) main: 0> hist --replay 9708
hello world
=> nil
[41] (pry) main: 0> 

, , up arrow ( - ), : hist --replay -1. , wiki hist.

+6

( ) , , , , Ctrl + R, .

, GNU Readline, . .

+3

, - (, gdb), , , .

, , ; IRB.CurrentContext.io.line,

eval IRB.CurrentContext.io.line <line number>

. Hooopo, :

def r(number)
  eval IRB.CurrentContext.io.line number
end

ruby-1.9.3-p0 :004 > puts "hello"
hello
 => nil 
ruby-1.9.3-p0 :005 > r 004 # (or 'r 4')
hello
 => nil 
+2

.

IRB _. .

1.9.3p194 :001 > 2 + 2
 => 4 
1.9.3p194 :002 > _
 => 4 
1.9.3p194 :003 > _ * 3
 => 12 
1.9.3p194 :004 > _
 => 12 

, rails console.

+2

irb REPL , , , , . pry REPL replay.

+1

backtrace irb,

irb --tracer

irb. ( Ruby 2.3.3)

0

All Articles