2012-05-26 13 views
2

IRB是一種在Ruby中玩弄和測試事物的好方法。它也可以使用腳本做一些設置,像這樣:然而,新的IRB會話如何獲取其變量範圍?

require 'irb' 

class Pirate 
    def greet 
    puts "Arrrrr, nice to meet ya" 
    end 
end 

IRB.start # You can now instantiate Pirate in IRB 

有一件事我在不清楚,是可變的範圍做這個的時候。如果我IRB.start前添加這些行:

smithy  = Pirate.new 
@blackbard = Pirate.new 

... @blackbeard將在IRB可用,但引用smithy會得到undefined local variable or method 'smithy' for main:Object

爲什麼?

回答

6

Binding用來評估代碼是建立在irb/workspace.rb:51(我指的是紅寶石1.9.3 REV 35410這裏):

@binding = eval("def irb_binding; binding; end; irb_binding", 
       TOPLEVEL_BINDING, 
       __FILE__, 
       __LINE__ - 3) 

這意味着,在相同的IRB會話運行上下文作爲頂級方法中的代碼。觀察:

puts "Outer object ID: %d" % self.object_id 
puts "Outer binding: " + binding.inspect 
smithy  = Pirate.new 
@blackbard = Pirate.new 

def test 
    puts "Inner object ID: %d" % self.object_id 
    puts "Inner binding: " + binding.inspect 
    p @blackbard 
    p smithy 
end 
test 

輸出:

Outer object ID: 13230960 
Outer binding: #<Binding:0x00000001c9aee0> 
Inner object ID: 13230960 
Inner binding: #<Binding:0x00000001c9acd8> 
#<Pirate:0x00000001c9ada0> 
/test.rb:18:in `test': undefined local variable or method `smithy' for main:Object (NameError) 
    ... 

注意,對象上下文(self)是相同的內部和外部的功能。這是因爲每個頂級方法都被添加到全局的main對象中。

另請注意,該方法內部和外部的綁定不同。在Ruby中,每個方法都有自己的名稱範圍。這就是爲什麼你不能從IRB內部訪問本地名字,而你可以訪問實例變量。

說實話,IRB並不是Ruby軟件中最光榮的一塊。我通常使用Pry對於這種東西,使用它你可以做:

require 'pry' 
binding.pry 

,並與訪問當前的局部變量的會話。

+0

非常有見地。 – Renra

+0

+1,Pry,hehe:P – horseyguy