From: Robert Klemme Date: 2004-07-06T22:32:39+09:00 Subject: Re: Array::index and rindex operator "David A. Black" schrieb im Newsbeitrag news:Pine.LNX.4.44.0407060521080.8383-100000@wobblini... > 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' :-) Thanks for that correction! > 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 True. The approach is betters suited to a method implementation: module Enumerable def index_2(obj=nil, &b) b = lambda {|x| obj == x} unless b inject(0) {|i,el| return i if b.call(el); i+1} nil end end Thx for correcting my sloppyness. robert