Understanding 'require'

I am clearly missing something WRT ‘require’. I have a program file
(test1) which requires another file (test1a.rb). My content, etc. is
shown below. Why doesn’t running test1 produce, ‘Hello, world!’ as
output? Thanks for any input.

    ... doug

$ ls
test1 test1a.rb
$ cat test1a.rb
var1=‘Hello, world!’
$ cat test1
#!/usr/bin/ruby

require ‘./test1a.rb’
puts(var1)
$ ./test1
./test1:4: undefined local variable or method `var1’ for main:Object
(NameError)
$

Try this instead:

test1a.rb

VAR_ONE = “Hello, world!”

#test1
#!/usr/bin/env ruby
require ‘./test1a’
puts VAR_ONE

$./test1
#=> Hello, world!

This is because Kernel#require, and also, Kernel#load will never leak
local variables into the global namespace.

Kernel#require and #load will however leak constants, and ofcourse
globals, but Kernel#load will wrap the source in an anonymous module
preventing global namespace leaking if you pass ‘true’ as the second
argument (ie: load(’./test1a.rb’, true) should result in a NameError
“uninitialized constant”; just make sure you include the ‘.rb’ with
load)

OMG! I researched many posts and articles relating to the topic of
‘require’ before posting here. None of them mentioned anything about
this aspect of ‘require’. Everything I read led me to believe that when
I ‘require’ a file, the contents of the file is inserted into the source
code at that point as though it had simply been typed into the source
code directly. Now I don’t know if there is a way to do that (i.e.,
simply “include” the contents of a file in the source code). I was a
little confused about what you were trying to tell me about ‘load’; but,
I don’t think you were telling me that it would accomplish that purpose.
It would be nice to know if there is any way to accomplish this
objective.

This is a total game changer for me. I’m going to have to return to the
drawing board and access whether (in light of this new knowledge) there
is a better way for me to accomplish what I am trying to accomplish. I
may well be back for additional help. However, I think you have fully
clarified this particular issue. Thanks for the input.

  ... doug

On 01/18/2012 06:45 PM, Doug J. wrote:

var1=‘Hello, world!’
$ cat test1
#!/usr/bin/ruby

require ‘./test1a.rb’
puts(var1)
$ ./test1
./test1:4: undefined local variable or method `var1’ for main:Object
(NameError)
$

var1 is not a global variable, but is instead scoped only to the content
of test1a.rb. If you want to output it from test1 then you would need to
declare it as:

$var1=‘Hello, world!’

The $ makes it global.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs