W
William James
2007/8/14 said:I wanted to write a simple method for comparing two paths on a Windows
system. My initial algorithm felt very contrived:def same_path?(a, b)
a, b = [a, b].map{ |p| File.expand_path(p).downcase }
a == b
endIt felt like saving the result from #map and then doing the comparison
shouldn't be necessary. So I came up with the following solution:class Array
def apply(method)
shift.send(method, *self)
end
endThis allowed me to define #same_path? thusly:def same_path?(a, b)
[a, b].map{ |p| File.expand_path(p).downcase }.apply==)
endwhich, to me, looks a lot nicer. Array#apply takes a method (in a
symbolic manner) and applies it to its first element, passing the rest
of the elements as arguments to the given method.Any thoughts? Is Array#apply a method that could potentially have
other uses than my specific example above?
Your method should be called "apply!" because it's destructive. I'd
rather not do it that way, i.e. without changing the array at hand.You
can use inject for that.
I'd use #inject for your problem:
match = [a,b].map {|x| File.expand_path(x).downcase}.inject {|x,y| x==y}
match = [a,b].map {|x| File.expand_path(x).downcase}.uniq.size == 1