2010-04-23 27 views
15

文件welcome.rb包含:如何訪問我在IRB中需要的Ruby文件中定義的變量?

welcome_message = "hi there" 

但在IRB,我無法訪問我剛創建的變量:

require './welcome.rb' 

puts welcome_message 

# => undefined local variable or method `welcome_message' for main:Object 

什麼是預定義變量帶來的最佳方式,並有初始化工作require什麼時候進入IRB會話?全局變量似乎不是正確的路徑。

回答

14

雖然這是事實,你不能訪問所需的文件中定義的局部變量,你可以訪問常量,您可以訪問存儲在你必須在兩種情況下訪問對象什麼。因此,根據您的目標,有幾種分享信息的方式。

最常見的解決方案可能是定義一個模塊並將共享值放在那裏。由於模塊是常量,因此您可以在需要的上下文中訪問它。

# in welcome.rb 
module Messages 
    WELCOME = "hi there" 
end 

# in irb 
puts Messages::WELCOME # prints out "hi there" 

你也可以把這個值放到一個類裏面,效果差不多。或者,您可以將其定義爲文件中的常量。由於默認上下文是Object類的一個對象,稱爲main,您還可以在main上定義一個方法,實例變量或類變量。所有這些方法最終都會以不同的方式製造「全局變量」,或多或少,並且可能不適用於大多數目的。另一方面,對於具有非常明確的範圍的小型項目,它們可能沒有問題。

# in welcome.rb 
WELCOME = "hi constant" 
@welcome = "hi instance var" 
@@welcome = "hi class var" 
def welcome 
    "hi method" 
end 


# in irb 
# These all print out what you would expect. 
puts WELCOME 
puts @welcome 
puts @@welcome 
puts welcome 
+2

不錯,作爲一個評論:約翰海蘭的代碼中的'WELCOME'可以被訪問,因爲它由* upcase *字母開頭,這使它成爲一個常量。 Ruby是有趣的。 – 2012-10-20 17:38:21

2

我認爲最好的方法是這樣定義

class Welcome 
    MESSAGE = "hi there" 
end 

一類,那麼在IRB你可以打電話給你這樣的代碼:

puts Welcome::MESSAGE 
2

這至少應該能夠從IRB經驗:

def welcome_message; "hi there" end 
3

您無法訪問在包含文件中定義的局部變量。您可以使用高德:

# in welcome.rb 
@welcome_message = 'hi there!' 

# and then, in irb: 
require 'welcome' 
puts @welcome_message 
#=>hi there! 
相關問題