我可以在irb中重复命令吗?

Rob*_*nru 6 ruby irb

有没有一种简单的方法可以在Ruby irb中重复上一个命令?我希望在Unix中使用感叹号(!).

谢谢.

Hoo*_*opo 11

def repeat_last_irb
  eval(IRB.CurrentContext.io.line(-2))
end
Run Code Online (Sandbox Code Playgroud)

然后你可以使用replat_last_irb你的irb控制台来运行最后一个输入.

IRB.CurrentContext.io如下所示:

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 > "> 
Run Code Online (Sandbox Code Playgroud)

此对象保存所有io信息,并使用线方法获取您输入的每一行.

所以,我们可以使用eval重复上一次输入.


sep*_*eph 8

向上箭头逐行获取历史记录.Pry有更多的好东西,但我还没有尝试过.

  • @ d11wtq - 如果有兴趣(osx特定),请在此处找到答案:http://hints.macworld.com/article.php?story = 20088013133705760 (2认同)

hor*_*guy 6

除了按向上箭头并输入之外,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> 
Run Code Online (Sandbox Code Playgroud)

您只需传递要重播的代码play -i的表达式编号([]与提示相邻的编号).

有关该play命令的更多信息,请参阅维基页面,查看输入输入以了解与使用和操作输入历史相关的其他技巧

或者,如果您只想重播各个历史记录行,可以先使用该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> 
Run Code Online (Sandbox Code Playgroud)

或者,如果您只想重播最后一行输入,并且您不想使用up arrow(无论出于何种原因),那么只需使用:hist --replay -1.与往常一样,wiki包含有关hist命令的更多信息.