开发者

Accessing variables from included files in Ruby

How do you access variables which are defi开发者_Python百科ned in an included file?

# inc.rb
foo = "bar";


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

# NameError: undefined local variable or method `foo' for main:Object


You can't access a local outside of the scope it was defined in — the file in this case. If you want variables that cross file boundaries, make them anything but locals. $foo, Foo and @foo will all work.

If you just really don't want to put any sort of decoration on the symbol (because you don't like the way it reads, maybe), a common hack is just to define it as a method: def foo() "bar" end.


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"


I usually just define them as methods. Similar to what nickf said.

File1:

def static_path
  '/opt/foo'
end

File2:

static_path

Then just add a:

require_relative 'file path/file name' or require_relative 'file name' <= if files are in same dir.

to the file you want to use the method/variable in.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜