Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing variables from included files in Ruby

Tags:

include

ruby

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 local variable or method `foo' for main:Object
like image 445
nickf Avatar asked May 18 '10 01:05

nickf


1 Answers

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.

like image 112
Chuck Avatar answered Oct 12 '22 14:10

Chuck