开发者

access scope of 'required' files to get variables

If I require 'helper_file' in a开发者_如何学JAVA program and there are constants and variables declared in that required file is there a way to access those variables and constants?

require 'helper_file'

...some nice code

x = ConstantFromRequireFile


You use require to load a library into your Ruby program. It will return true if successful.

So you have a file 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."

and a file library.rb:

CONSTANTFROMREQUIREFILE = "Hello World"

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

As you can see you access the constant and the method as you would access a constant and a method from the same file.

You can read more about require here: What is the difference between include and require in Ruby? and here: Kernal Module in Ruby


constants, global variables, instance variables and class variables defined in the top level scope in a required file will all be available in the scope of the requiring file, but local variables will not. What exactly is your problem?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜