2017-01-16 149 views
2

我想要访问在顶层主要对象中定义的变量和方法在程序EVAL和红宝石绑定

@x = :hello 

def instanceMethodMain 
p "instanceMethodMain" 
end 

class Baz 
    def method 
    p eval("@x", TOPLEVEL_BINDING) 
    p eval("instanceMethodMain", TOPLEVEL_BINDING) 
    end 
end 

Baz.new.method 

输出是

:hello 
"instanceMethodMain" 
"instanceMethodMain" 

的输出是相同的,即使我使用

mainRef=TOPLEVEL_BINDING.eval('self') 
p mainRef.send :instanceMethodMain 

有人可以解释为什么instanceMethodMain被调用两次。

回答

3

instanceMethodMain不被调用两次。

您可以通过添加

def instanceMethodMain 
    puts "BEEN HERE" 
    p "instanceMethodMain" 
end 

p检查与"instanceMethodMain"作为参数调用两次。

p p "instanceMethodMain" 
#=> "instanceMethodMain" 
#=> "instanceMethodMain" 

注意p "string"显示器"string"返回"string",而puts "string"显示器string并返回nil

puts puts "instanceMethodMain" 
#=> instanceMethodMain 
#=> 
1

"instanceMethodMain"被打印的两倍,因为双p

p eval("instanceMethodMain", TOPLEVEL_BINDING) 

被翻译成

p p "instanceMethodMain" 
#=> "instanceMethodMain" 
#=> "instanceMethodMain" 

删除任何一个会打印"instanceMethodMain"只有一次:

def instanceMethodMain 
    "instanceMethodMain" 
end 


Baz.new.method 
#=> :hello 
#=> "instanceMethodMain"