2011-10-10 23 views

回答

4

您可以使用require將庫加載到Ruby程序中。如果成功,它將返回true。

所以,你有一個文件example.rb

require 'library.rb' 

# Some code 

x = CONSTANTFROMREQUIREFILE 

puts x # "Hello World" 

method_from_required_file # "I'm a method from a required file." 

library.rb文件:

CONSTANTFROMREQUIREFILE = "Hello World" 

def method_from_required_file 
    puts "I'm a method from a required file." 
end 

正如你可以看到你訪問常數和方法你可以從同一個文件中訪問一個常量和一個方法。

你可以閱讀更多有關要求的位置:What is the difference between include and require in Ruby?這裏:Kernal Module in Ruby

+0

謝謝,這是完美的。 – slindsey3000

2

常量,全局變量,實例變量,類變量在頂級的範圍定義在一個必需的文件都將在需要文件的範圍內都有效,但局部變量不會。你的問題到底是什麼?

+0

這回答了這個問題。我誤解了涉及的範圍。謝謝。 – slindsey3000