Accessing variables from included files in Ruby

前端 未结 3 618
孤城傲影
孤城傲影 2020-12-31 17:10

How do you access variables which are defined in an included file?

# inc.rb
foo = \"bar\";


# main.rb
require \'inc.rb\'
puts foo

# NameError: undefined lo         


        
3条回答
  •  不知归路
    2020-12-31 18:05

    I've accepted Chuck's answer because it's a decent solution, however I actually used a different method, which I thought I'd share. It's incredibly hacky, but was useful for my purposes. I needed to scan a directory with hundreds of files, each of which created an object with the same name, and then dump some info about each object. For any serious and non-temporary purposes, I would not recommend this!

    foo = ""
    eval File.open('inc.rb').read
    
    puts foo # "bar"
    

提交回复
热议问题