creating file names with string

J

John Maclean

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
 
A

Alex Combas

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=3Dfile
end

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

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

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

data =3D "/home/flubber/greppa.rb"

i =3D Greppa.new(data)
i.grabber
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,280
Latest member
BGBBrock56

Latest Threads

Top