How to use global variables in Ruby

ruby

Solution

`tmp_dir` is defined as a variable in the class definition, but in the instance function you're looking for a `tmp_dir` defined on an instance of the class. That's why `tmp_dir` is undefined inside the function.

You can make it global or make it a class variable as quick fixes. I think there's a better alternative: wrap this up in its own class that knows how to cache, and then initialize `tmp_dir` without making it global OR a class variable:

class Cacher
    def initialize(tmp_dir)
        @tmp_dir = tmp_dir
    end

    def cache(page)
        wget "#{@tmp_dir}/page"
    end
end

# in your main file:
cacher = Cacher.new('/path/to/tmp/dir') # here's your configuration line, but with no global!

# later

cacher.cache("index.html")

Problem

I have a situation where I define a variable at the top of my script, and want to reference it in a method: ``` ############# # Variables # ############# tmp_dir = '/path/to/tmp/dir' ########### # Methods # ########### def cache(page) begin %x[wget -q -O #{tmp_dir}/page #{page}] rescue => msg puts "error: #{msg}" exit end end cache("http://somepage.com") ``` I am getting this error: ``` undefined local variable or method `tmp_dir' for main:Object ``` I'm guessing I need to make `tmp_dir` a global variable? I hate using global variables. Is there a Ruby-ish way to do this?

Original source