From: Logan Capaldo Date: 2007-03-01T05:38:14+09:00 Subject: Re: Overload [] operator and use a block ? ------=_Part_21529_31853266.1172695088638 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: quoted-printable Content-Disposition: inline On 2/28/07, Robert Klemme wrote: > > On 28.02.2007 21:15, St=E9phane Wirtel wrote: > > I would like to know if it's possible to overload the [] operator to > > use a block with it. > > > > example: > > > > class Test > > def []( x ) > > # to do something here > > yield if block_given? > > end > > end > > > > t =3D Test.new > > t['string'] do > > puts 'this is a test' > > end > > AFAIK it's not because the syntax does not allow a block with []: > > irb(main):001:0> o=3DObject.new > =3D> # > irb(main):002:0> def o.[](x) > irb(main):003:1> yield x > irb(main):004:1> end > =3D> nil > irb(main):005:0> o[1] {|*a| p a} > SyntaxError: compile error > (irb):5: parse error, unexpected '{', expecting $ > o[1] {|*a| p a} > ^ > from (irb):5 > from :0 > > Kind regards > > robert Yep. You can however do t.send(:[], 'string') do puts "This kind of defeats the purpose" end ------=_Part_21529_31853266.1172695088638--