Sunday, March 15, 2009

Variation on index method from Class String

Ok, so I wanted to find the indices of all occurrences of String 'A' within a larger String 'B'. The Ruby core String class's index and rindex methods do this for one value, but not for all of them.

A recursive solution made the most sense (note: ternary operator has to be on one line):
def indices(str, pos = 0)
!self.index(str, pos).nil? /
? (self.indices(str, self.index(str, pos) + 1) /
| [].push(self.index(str, pos))).sort : []
end
That gives an array of all of the indices in sorted order, and is actually quite cryptic. Here's a more readable version:
def indices(str, pos = 0)
if (!self.index(str, pos).nil?)
# Get the position of the current find
x = self.index(str, pos)
# Return the union of what you found
# and look for more occurrences
[].push(x) | self.indices(str, x + 1)
else
# Basecase. Return empty array for union "|"
[]
end
end

No comments:

Post a Comment