类 Binding
公共实例方法
irb(show_code: true) 点击切换源代码
打开一个 IRB
会话,其中调用 binding.irb
,以便进行交互式调试。您可以调用当前作用域中可用的任何方法或变量,并且如果需要,可以修改状态。
给定一个名为 potato.rb
的 Ruby 文件,其中包含以下代码
class Potato def initialize @cooked = false binding.irb puts "Cooked potato: #{@cooked}" end end Potato.new
运行 ruby potato.rb
将打开一个 IRB
会话,其中调用 binding.irb
,您将看到以下内容
$ ruby potato.rb From: potato.rb @ line 4 : 1: class Potato 2: def initialize 3: @cooked = false => 4: binding.irb 5: puts "Cooked potato: #{@cooked}" 6: end 7: end 8: 9: Potato.new irb(#<Potato:0x00007feea1916670>):001:0>
您可以输入任何有效的 Ruby 代码,它将在当前上下文中进行评估。这允许您进行调试,而无需重复运行您的代码
irb(#<Potato:0x00007feea1916670>):001:0> @cooked => false irb(#<Potato:0x00007feea1916670>):002:0> self.class => Potato irb(#<Potato:0x00007feea1916670>):003:0> caller.first => ".../2.5.1/lib/ruby/2.5.0/irb/workspace.rb:85:in `eval'" irb(#<Potato:0x00007feea1916670>):004:0> @cooked = true => true
您可以使用 exit
命令退出 IRB
会话。请注意,退出会恢复 binding.irb
暂停的执行,如本例中打印到标准输出的输出所示
irb(#<Potato:0x00007feea1916670>):005:0> exit Cooked potato: true
有关更多信息,请参阅 IRB
。
# File irb.rb, line 1563 def irb(show_code: true) # Setup IRB with the current file's path and no command line arguments IRB.setup(source_location[0], argv: []) unless IRB.initialized? # Create a new workspace using the current binding workspace = IRB::WorkSpace.new(self) # Print the code around the binding if show_code is true STDOUT.print(workspace.code_around_binding) if show_code # Get the original IRB instance debugger_irb = IRB.instance_variable_get(:@debugger_irb) irb_path = File.expand_path(source_location[0]) if debugger_irb # If we're already in a debugger session, set the workspace and irb_path for the original IRB instance debugger_irb.context.replace_workspace(workspace) debugger_irb.context.irb_path = irb_path # If we've started a debugger session and hit another binding.irb, we don't want # to start an IRB session instead, we want to resume the irb:rdbg session. IRB::Debug.setup(debugger_irb) IRB::Debug.insert_debug_break debugger_irb.debug_break else # If we're not in a debugger session, create a new IRB instance with the current # workspace binding_irb = IRB::Irb.new(workspace, from_binding: true) binding_irb.context.irb_path = irb_path binding_irb.run(IRB.conf) binding_irb.debug_break end end