From: Logan Capaldo Date: 2007-07-10T09:51:40+09:00 Subject: Re: Syntax sugar: method[](...) => method(...) ------=_Part_21425_29873500.1184028701621 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline On 6/29/07, Erwin Abbott wrote: > > Hi, > > The [] method is really handy when you have an object that should > behave like a hash or array. One thing I find myself wishing I could > also do is something like > > def logins[](date) > @events.select{|e| e.action == :login and e.date == date} > end class Module def bracket(name, &code) define_method("#{name}_bracketed", &code) m = instance_method("#{name}_bracketed") remove_method "#{name}_bracketed" define_method(name) do || obj = Object.new m1 = m.bind(self) (class << obj; self; end).module_eval { define_method(:[]) { |x| m1[x] } } obj end end end class Foo bracket :logins do |date| @data.select { |e| e.date == date } end end Who needs sugar? (I so didn't test this at all) There may be a better way to deal with this example, but this is just > to demonstrate the circumstances where you don't have an array or hash > called logins, but you'd like to be able to use that [] syntax. One > way I though about doing it is > > def logins > EventList.new @events.select{|e| e.action == :login} > end > > class EventList > def initialize data > @data = data > end > def [] date > @data.select{|e| e.date == date} > end > end > > logins[Date.today] # => all logins today from @events > > I guess some people might prefer to write a method like > get_logins(date), but I like this syntax. It seems reasonable to also > define []= in EventList to update the original @events. What I'd like > to know is if there's another way to solve this problem, or if there > are any simple optimizations (maybe only keep one instance of > EventList and update its contents with each call to #events). > > Lastly, has there been any mention of allowing function names like so > in ruby 1.9: > def logins[] date > # ... > end > > Thanks, > - Erwin > > ------=_Part_21425_29873500.1184028701621--