From: "David A. Black" Date: 2007-10-09T19:26:58+09:00 Subject: Re: Indexers and blocks? Hi -- On Tue, 9 Oct 2007, Stephan Mueller wrote: > Hi, > > if I have an array-like class, is it possible to call the index with a > block? > > class MyClass > def find(key) > return nil > end > > def [](key) > if (val = find(key)) > return val > else > return yield(key) if block_given? > end > end > end > > c = MyClass.new > c[:test] { "default" } > > triggers a syntax error (Ruby 1.8.6). > > Is there a way to accomplish this or do i need to do tricks like giving > the block to the constructor? You can do: c.[](:text) { "default" } but that's kind of ugly. I guess the whole point of c[] is to conceal the fact that it's a method call, which means that it then doesn't try to duplicate the full method call anatomy. David -- Upcoming training from Ruby Power and Light, LLC: * Intro to Ruby on Rails, Edison, NJ, October 23-26 * Advancing with Rails, Edison, NJ, November 6-9 Both taught by David A. Black. See http://www.rubypal.com for more info!