From: Robert Klemme Date: 2004-09-20T00:39:42+09:00 Subject: Re: Array#index block and rdetect "trans. (T. Onoma)" schrieb im Newsbeitrag news:200409191019.59425.transami@runbox.com... > On Sunday 19 September 2004 07:59 am, Robert Klemme wrote: >> "trans. (T. Onoma)" schrieb im Newsbeitrag >> news:200409190606.22327.transami@runbox.com... >> >> > Tiny RCR suggestion: >> > >> > Array#index optionally take a block like Enumerable#detect does. >> > >> > ['a','b','c'].index{|e| e == 'b'} # => 1 >> > ['a','b','c'].index{|e| e == 'c'} # => 2 >> > ['a','a','a'].index{|e| e == 'a'} # => 0 >> > ['a','a','a'].index{|e| e == 'b'} # => nil > > But this Array#index {block) is acceptable, yes? Yes, I think that could be useful. >> > Question: why isn't #index a method of Enumerable, considering >> > #each_with_index is? (FYI: 'alias find detect'.) >> >> Because not all collections keep a definite order as Array does. For >> example, hashes do not keep any certain order of elements hence indexing >> does not make any sense. > > Couldn't the index of a hash be considered the key? So the block of #index > when applied is the value. i.e. Good idea! That way Hash and Array are partly interchangable. You could view an array as a special case of an associative storage with the restriction that keys are ints. > {:a=>'a',:b=>'b',:c=>'b'}.index{|e| e == 'b'} # => :b > > But then, of course, there would be no telling which key you might get. > Suppose that could be considered a problem. The same holds for #index so I think this is not a problem. You only get one key, presumably the first that is found. Same story for Array#index: >> %w{a a a a}.index "a" => 0 >> class Hash >> def index(val) >> each {|k,v| return k if val == v} >> nil >> end >> end => nil >> {1=>"a", 2=>"a"}.index "a" => 1 >> {1=>"a", 2=>"a"}.index "ad" => nil >> > Lastly, what about an rdetect? >> >> Not in Enumerable because each only iterates in one direction. (Ok, you >> could go through it an output the last but that would not work for >> Enumerables that return infinite elements.) > > I see. > > Hmm... sometimes it seems like these are quite categorized as finely as > they > might be. Yes, definitely! That's what I discovered, too, when I suggested Enumerable#size and Enumerable#empty? They just need more preconditions than Enumerable. Matz did really a great job here! Kind regards robert