2

If I require 'helper_file' in a 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

slindsey3000
  • 4,053
  • 5
  • 36
  • 56

2 Answers2

4

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

Community
  • 1
  • 1
2

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?

riffraff
  • 2,429
  • 1
  • 23
  • 32