简体   繁体   English

我如何使用 irb Ruby 解释器来测试/调试 my.rb 文件?

[英]How can I use irb the Ruby interpreter to test/debug my .rb files?

How can I use irb the Ruby interpreter to test/debug my .rb files?我如何使用 irb Ruby 解释器来测试/调试我的.rb文件? I want to load an .rb file, let it run, and after it ends, get back to the irb prompt so I would be able to manipulate the variables which my script has built.我想加载一个.rb文件,让它运行,并在它结束后返回到 irb 提示符,这样我就能够操纵我的脚本构建的变量。

I tried load , require , and irb -r , but none of them worked as I would like.我尝试了loadrequireirb -r ,但它们都没有像我希望的那样工作。 After the execution, when the program terminates, I get an irb prompt, but all of the variables are inaccessible.执行后,当程序终止时,我得到一个 irb 提示,但所有变量都无法访问。 What can I do?我能做什么?

不确定确切要做什么,但听起来您可能想使用“撬”宝石。

  1. Install the pry gem see: http://pryrepl.org 安装pry宝石,请参见: http : //pryrepl.org
  2. require 'pry' at the start of your program. 在程序开始时要求“撬”。
  3. put binding.pry at the end of your program (or where you want to start the interactive session) binding.pry放在程序的末尾(或您要开始交互式会话的位置)
  4. run your program. 运行您的程序。

Using pry you will have all your variables in scope. 使用pry,您将在范围内拥有所有变量。

More information see the link above, and here: 有关更多信息,请参见上面的链接,以及此处:

http://banisterfiend.wordpress.com/2011/01/27/turning-irb-on-its-head-with-pry/ http://banisterfiend.wordpress.com/2011/01/27/turning-irb-on-its-head-with-pry/

and: 和:

https://github.com/pry/pry/wiki/Runtime-invocation https://github.com/pry/pry/wiki/Runtime-invocation

If the variables you want are local variables, I do not think there is a way you can access them from another file. 如果您想要的变量是局部变量,那么我认为您无法通过其他文件访问它们。

If you just want the return value of the whole code that is on a different file, you can eval the whole content of that file within the main code and access the return value. 如果只希望整个代码位于不同文件中的返回值,则可以在主代码中eval该文件的全部内容并访问该返回值。 You can access multiple values by putting them in an array or a hash at the end of the file to be eval ed. 您可以通过将多个值放在要eval的文件末尾的数组或哈希中来访问多个值。

Add following code in place where you want irb to start 在希望irb开始的位置添加以下代码

require 'irb'
IRB.start(__FILE__)

binding.irb

As of Ruby 2.4, placing this in your code will drop you into an irb session in the scope where it is placed.从 Ruby 2.4 开始,将其放入您的代码中将使您进入放置它的 scope 中的 irb session。

No additional gem installs or require statements are needed.不需要额外的 gem 安装或 require 语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM