From: "nikolai.weibull@..." Date: 2007-08-14T20:59:58+09:00 Subject: Re: Does an Array#apply make any sense at all? On Aug 14, 1:51 pm, "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'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} Ah, I had no idea inject would take the first item of an array if not given an argument; thanks! That solves my problem. nikolai