Hi Richard,
Happy to help.
I would definitely encourage you to not only look at design patterns
(which are okay, but often overkill or already built in to Ruby) but
also to Ruby’s standard features to reduce code errors.
Ruby is a rich language. It has a lot of really well-crafted methods
that take care of a most of the tedium of coding, and for that reason
the standard library is well worth learning.
For example, in your code, instead of importing ‘find’ and using it to
look at directories, use Ruby’s built-in Dir module. Dir[’**/*’] will
get you all subdirectories and files recursively.
Second, look into higher order functions. They let you change code from
this:
def evaluate(dir, arg)
results = []
Dir[’**/*’].each do |p|
next unless File.file? p
name = File.basename§
case arg
when String
results << p if File.fnmatch(@arg, name)
when Regexp
results << p if @arg.match(name)
end
end
results
end
Into this:
def match?(str_or_re, file)
str_or_re.is_a?(String) ? File.fnmatch(str_or_re, file) : str_or_re =~
file
end
def evaluate(dir, arg)
Dir[’**/*’].select {|f| File.file?(f) and match?(arg, f) }
end
Any time you see this pattern …
my_temporary_variable = []
my_collection.each do |elem|
my_temporary_variable << elem if some_condition
end
return my_temporary_variable
… you know that higher order functions would probably be a better
solution.
Hope that helps, and good luck learning this beautiful language.
Cheers,
David
Any time you see this pattern in your code, you should automatically
think