From: Farrel Lifson Date: 2007-11-21T02:12:16+09:00 Subject: Re: Quick way to get attributes (without using collect) On 20/11/2007, Max Williams wrote: > This was inspired by Rails, but i think it's common Ruby question. Say > i have an array of Employee objects, which have an attribute "name". I > want to get all the names, as an array. > > Let's say i already have the variable "employees", which points to an > array of Employee objects. > > What i want to do is something like this - > > employee_names = employees.names > > But what i have to keep on doing is something like this - > > employee_names = employees.collect{ |emp| emp.name} > > Now, this isn't a *massive* hassle, and i find Array#collect incredibly > useful, but it's a bit annoying to have to keep typing it again and > again. Is there a way to set it up so that > > .foos > > is automatically treated as > > .collect { |x| x.foo } > > ? > > Or another way to do this simply? You can use the Symbol#to_proc method class Symbol def to_proc Proc.new {|e| e.send(self)} end end Which will let you right employee_names = employees.collect(&:name) Farrel