From: "nikolai.weibull@..." Date: 2007-08-14T23:29:57+09:00 Subject: Re: Does an Array#apply make any sense at all? On Aug 14, 2:07 pm, dbl...@rubypal.com wrote: > Hi -- > > > > On Tue, 14 Aug 2007, Robert Klemme wrote: > > 2007/8/14, nikolai.weib...@gmail.com : > >> Hi! > > >> 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 > >> end > > >> It 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 > >> end > > >> This allowed me to define #same_path? thusly: > > >> def same_path?(a, b) > >> [a, b].map{ |p| File.expand_path(p).downcase }.apply(:==) > >> end > > >> which, 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 could be wrong, but I think the convention (at least in core Ruby) > is that ! methods always come in a pair with the non-! version. I > don't think there are any cases where there's just a method called m! > where the ! indicates destructiveness (or other "danger"). All the > unpaired destructive methods have non-! names. Ugh. This was so NOT about whether to call the method Array#apply or Array#apply!. I just wrote the absolute shortest solution I could think of. I didn't suggest that it was the final version. Yes, seeing as how my definition mutates its target, Array#apply! is the appropriate name. I simply didn't want to clutter the definition thusly: class Array def apply(method) first.send(method, *self[1..-1]) end end (which sort of begs the question why we don't have Array#rest ;-) nikolai