Jayson Rowe
Jayson Rowe

Reputation: 123

Accessing/Dealing with Variables in Ruby

Let me preface by stating I'm a "new" programmer - an IT guy trying his hand at his first "real" problem after working through various tutorials.

So - here is what I'm trying to do. I'm watching a directory for a .csv file - it will be in this format: 999999_888_filename.csv

I want to return each part of the "_" filename as a variable to pass on to another program/script for some other task. I have come up w/ the following code:

require 'rubygems'
require 'fssm'

class Watcher

def start
  monitor = FSSM::Monitor.new(:directories => true)
  monitor.path('/data/testing/uploads') do |path|
    path.update do |base, relative, ftype| 
      output(relative)
    end
    path.create do |base, relative, ftype| 
      output(relative)
    end
    path.delete { |base, relative, ftype| puts "DELETED #{relative} (#{ftype})" }   
  end
  monitor.run
end


def output(relative)
  puts "#{relative} added"
  values    = relative.split('_',)
  sitenum  = values[0]
  numrecs  = values[1]
  filename = values[2]
  puts sitenum
 end
end

My first "puts" gives me the full filename (it's just there to show me the script is working), and the second puts returns the 'sitenum'. I want to be able to access this "outside" of this output method. I have this file (named watcher.rb) in a libs/ folder and I have a second file in the project root called 'monitor.rb' which contains simply:

require './lib/watcher'

watcher = Watcher.new
watcher.start

And I can't figure out how to access my 'sitenum', 'numrecs' and 'filename' from this file. I'm not sure if it needs to be a variable, instance variable or what. I've played around w/ attr_accessible and other things, and nothing works. I decided to ask here since I've been spinning my wheels for a couple of things, and I'm starting to confuse myself by searching on my own.

Thanks in advance for any help or advice you may have.

Upvotes: 2

Views: 104

Answers (2)

megas
megas

Reputation: 21791

In addition to Jordan Scales' answer, these variable should initialized

class Watcher
  attr_accessor :sitenum, :numrecs, :filename

  def initialize
    @sitenum = 'default value'
    @numrecs = 'default value'
    @filename = 'default value'
  end

  ...
end

Otherwise you'll get uninformative value nil

Upvotes: 2

Jordan Scales
Jordan Scales

Reputation: 2717

At the top of the Watcher class, you're going to want to define three attr_accessor declarations, which give the behavior you want. (attr_reader if you're only reading, attr_writer if you're only writing, attr_accessor if both.)

class Watcher
    attr_accessor :sitenum, :numrecs, :filename

    ... 
    # later on, use @ for class variables
    ...
        @sitenum = 5
    ...
end

Now you should have no problem with watcher.sitenum etc. Here's an example.

EDIT: Some typos.

Upvotes: 2

Related Questions