Creating file names with string

Hey chaps,

A script to ask a user for a string and use it to grep through a

file. My first version works.

It was suggested to turn the constants into objects whilst chatting on

ruby-lang. Please compare the two methods
(excuse the pun). What’s wrong with using constants and what am I doing
wrong in my OO version?

#first version using constants

DataDir= “/home/jayeola/bin/acid/data/lookups/”
DataFile = “lookup_assetype.txt”
Lookup = File.join(DataDir, DataFile)

def usage
screen = “type some letters in the word”
end

def grabber

grab first couple letters and grep thru file

xx = gets.chomp!
File.open("#{Lookup}") do |test|
test.each do |line|
puts line if line =~ /#{xx}/
end
end
end

puts usage
grabber

This doesn’t work. The “object” way…

def usage
screen = “type a few letters containing the word”
end

i = Greppa.new("{@datadir}", “{@datafile}”)
i.inspect
puts usage
puts lookup

filelocations

class Greppa
def initialize(datadir, datafile )
@datadir= “/home/jayeola/bin/acid/data/lookups/”
@datafile = “lookup_assetype.txt”
@lookup = File.join(@datadir, @datafile)
end
end

def grabber
lookup = File.join("{@datadir}", “{@datafile}”)

grab first couple letters and grep thru file

xx = gets.chomp!
File.open("#{lookup}") do |test|
test.each do |line|
puts line if line =~ /#{xx}/
end
end
end

i = Greppa.new("{@datadir}", “{@datafile}”)
i.inspect
puts usage
puts lookup

On 1/29/06, John M. [email protected] wrote:

Hey chaps,

Hi John,

(excuse the pun). What’s wrong with using constants and what am I doing
wrong in my OO version?

Well the first thing that struck me is that hardcoding the path
into the program you is not good, it would be a more useful
program if you could specify which file to search on the
command line as well as the regex in question.
I’ll leave implementing that method up to you.

I’m just learning myself, but I touched up your OO version
but kept your logic mostly intact.
Enjoy.

class Greppa
def initialize(file)
@f=file
end

def usage
print "(Greppa)Enter a regex:> "
end

def grabber
usage
xx = gets.chomp!
File.open(@f, ‘r’) do |test|
test.each do |line|
puts line if line =~ /#{xx}/
end
end
end
end

#Rather than hardcoding lets make a new method that
#asks the user for the data file

data = “/home/flubber/greppa.rb”

i = Greppa.new(data)
i.grabber