RCR 235: anArray.rekursive_index
Submitted by Icekiss (Sat Mar 27 15:03:29 UTC 2004)
Abstract
Add a new instance method to Array to allow a more powerfull way to search for a key.
Problem
It isn't currently trivially possible to search for a key in an array that contains subarrays.
Proposal
Add a new instance method rekursive_index to the Array class.
Interface:
rekursive_index(key) -> anArray<br>
This method would return an array, that contains the indexes of the arrays necessary to reach the key.
example:
a=[9, 7, 5, [1, 2], 3]
a.rekursive_index(1) -> [3, 0]
a.rekursive_index(7) -> [1]
a.rekursive_index(0) -> nil
a.rekursive_index([1,2]) -> [3]
Analysis
It isn't possible to just reimplement the index method to achieve this, because rekursive.index will return an Array with one element, where index would just return the element. And for consistencies sake, it has to be that way.
Implementation
class Array
def rekursive_index(key)
rIndex=nil
each_with_index do |element, index|
if element==key
rIndex=[index]
break
end
if element.kind_of?(Array)
rIndex=element.rekursive_index(key)
if rIndex
rIndex=[index]+rIndex
break
end
end
end
rIndex
end
end
I have discovered ruby 3 days ago, and I have to say: It is absolutely the best programming language I have ever seen. Just thought I share what usefull additions to the standard classes I can see. :-)
And a deep bow to matz for making this language available. *bow*
EDIT: I have found the <pre> tag to format my code sensibly. Great!
--Icekiss--
|
Strongly opposed |
1 |
Opposed |
1 |
Neutral |
0 |
In favor |
0 |
Strongly advocate |
0 |
|
This RCR has been superseded by RCR 236.
RCRchive copyright © David Alan Black, 2003-2005.
Powered by .
I have discovered ruby 3 days ago, and I have to say: It is absolutely the best programming language I have ever seen. Just thought I share what usefull additions to the standard classes I can see. :-)
And a deep bow to matz for making this language available. *bow*
EDIT: I have found the <pre> tag to format my code sensibly. Great!
--Icekiss--