如何在当前类的上下文中运行 IRB.start [英] How to run IRB.start in context of current class

查看:29
本文介绍了如何在当前类的上下文中运行 IRB.start的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚经历了 PragProg Continuous Testing With Ruby,他们讨论了在当前类的上下文中调用 IRB 来手动检查代码.

I've been just going through PragProg Continuous Testing With Ruby, where they talk about invoking IRB in context of current class to inspect the code manually.

然而,他们引用说,如果你在一个类中调用 IRB.startself 是预定义的,并且指的是我们在调用 start 时所在的对象 就我而言,这不是真的.

However, they quote that if you invoke IRB.start in a class, self is predefined, and refers to the object we were in when start was called which isn't true in my case.

即使是非常简单的例子,比如

Even for very simple example like

a = "hello"
require 'irb'
ARGV.clear # otherwise all script parameters get passed to IRB
IRB.start

当我尝试访问 a 变量时,我得到了明显的

When I try to access the a variable, I get the obvious

NameError: undefined local variable or method `a' for main:Object

仅当我将 a 更改为全局变量时才有效

It works only when I change a to global variable

$a = "hello"
require 'irb'
ARGV.clear # otherwise all script parameters get passed to IRB
IRB.start

然后我可以访问它

irb(main):001:0> $a
=> 1

有没有办法访问当前类中的局部变量和实例变量?

推荐答案

我建议在 ripl,irb 的替代品.上面的例子有效:

I'd suggest trying this in ripl, an irb alternative. The above example works:

a = 'hello'
require 'ripl'
Ripl.start :binding => binding

请注意,局部变量有效,因为您使用 :binding 选项传递当前绑定.

Note that local variables work because your passing the current binding with the :binding option.

你可以在 irb 中做同样的事情,但由于它的文档和未经测试,你完全没有机会做到这一点.

You could possibly do the same in irb, but since it's poorly documented and untested, your chances of doing it cleanly are slim to none.

这篇关于如何在当前类的上下文中运行 IRB.start的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆