From: "David A. Black" Date: 2008-04-30T23:07:09+09:00 Subject: Re: How to create "def method(item)= (value)" ? Hi -- On Wed, 30 Apr 2008, Phillip Gawlowski wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > David A. Black wrote: > > |> > |> Sort of. As a singleton method, you get the syntax error. But not if you > |> define [] as a method: > |> > |> irb(main):001:0> def []=(key,value) > |> irb(main):002:1> end > |> => nil > | > | It's not the singletonness that stops it; you can do this: > | > | def object.[]=(k,v) # etc. > | > | What made my example wrong was that I had concocted an illegal method > | name. > > Though, it should (might?) be possible to implemetn something like > Hash's or Array's > > hash[key] > array[index] > > index methods for plain old object instances, too. Sure: def object.[](index) # derive value you want here end And then: object[something] You always get the [] syntactic sugar for free when you define []. David -- Rails training from David A. Black and Ruby Power and Light: INTRO TO RAILS June 9-12 Berlin ADVANCING WITH RAILS June 16-19 Berlin INTRO TO RAILS June 24-27 London (Skills Matter) See http://www.rubypal.com for details and updates!