A recursive solution made the most sense (note: ternary operator has to be on one line):
def indices(str, pos = 0)That gives an array of all of the indices in sorted order, and is actually quite cryptic. Here's a more readable version:
!self.index(str, pos).nil? /
? (self.indices(str, self.index(str, pos) + 1) /
| [].push(self.index(str, pos))).sort : []
end
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