From: "David A. Black" Date: 2004-07-06T21:26:09+09:00 Subject: Re: Array::index and rindex operator Hi -- On Tue, 6 Jul 2004, Robert Klemme wrote: > > "Kristof Bastiaensen" schrieb im Newsbeitrag > news:pan.2004.07.06.10.51.04.229075@vleeuwen.org... > > Hi, > > > > On Tue, 06 Jul 2004 09:42:41 +1000, George Ogata wrote: > > > > > Sometimes though I wish that #index could take a block (i.e., return > > > the first index for which the block is true). Unless I'm overlooking > > > something, there doesn't seem to be a method that does this. I don't > > > know what others think of the idea, but that would probably go some > > > way towards your goal. > > > > I think that would be nice. I would vote for it. > > You could do this with enumerator, but it is not so compact: > > > > require "enumerator" > > > > a = %w(one two three) > > a.enum_for(:each_with_index).find { |s, i| s == "two" }[1] > > => 1 > > Another solution: > > a.inject(0) {|i,s| break i if "two" == s; idx+1} The problem though (aside from 'idx' for 'i' :-) is that you always get a number, even if there's no element found: [1,2,3].inject(0) {|i,s| break i if "two" == s; i + 1} # => 3 David -- David A. Black dblack@wobblini.net