Hello.
Brief disclaimer. I’m coming from a bourne shell back ground and
currently all of my ruby scripts look like shell scripts where I
create methods like i would a shell function and now that I understand
some of the language basics (variables, loops, exceptions) I want to
improve my skills and try to leverage the language instead of just
brute forcing my way through problems. I’m not looking for a one
liner wizardry solution but some help getting a better understanding
of classes and ruby in general to change my approach to writing ruby
scripts.
I’ve scaled down my project to the most basic components that will
still allow me to express my areas of confusion. I have a file that
changes daily which contains a list of people in this format
bob.smith
bill.johnson
betty.joe
tony.johnson
wilbur.smith
Additionally I have a directory populated with 1 file per uniq last
name (ie: smith, johnson, joe). I need to parse through the days list
and then cleanse the last name files of the previous entries and
insert the updated list. I’ve got the script that does this it is
not very efficient (ie: i must define all the last names in
advance). So now i’ve started to rewrite the script and this is
where I’m stuck
I just barely understand setter/getter enough so can create LastName
objects and then
read the @first or @last variables
class LastName
def initialize(n)
@first, @last = n.split(".")[0], n.split(".")[1]
end
attr_accessor :first, :last
def get_last
@last
end
end
Here I am trying to dynamically define all of the last name
variables which would contain
all of the strings that have the given last name.
nf = File.open(“people”, “r”)
surnames = []
nf.each_line do |l|
p = LastName.new(l)
sur = p.get_last
sur << l
surnames << sur
end
I try to access the various “sur” variables which should contain the
list of people with a specific last
name but cannot figure out how to call the specific instance of
“sur”. Is their some way I could
dynamically create the “sur” variable as say “smith” and then
include them in the “surnames”
array so later I could loop through the surnames.uniq array and get
the name of all the “sur”
variables. Here is my pseudo code
surnames.uniq.each do |s|
namefile = File.open(s,“w+”)
namefile << s
end
I realize that my problem is pretty rudimentary but so far i’ve only
been able to create basic classes
and instantiate 1 object at a time to understand the getter/setter
methods. Trying to iterate
through a list my pea brain gets mired in all the different objects
and how do I look at certain ones.
Anyhoo I’d appreciate comments on my specific dynamic variable
problem or any other pointers
to help my get to the “AH HA!” moment with constructing and using
classes which I feel I’m pretty close to.
TIA. G
ps: I own many ruby books and have spent about 20 hours trying to
solve this pretty basic situation and dont know where else to go for
help.