I have an array like this:
stuff = ["A", " ", "C", " ", "E", " ", "G"]
and I want to return an array of all the indexes where the data is a blank space say. Eg:
[1, 3, 5]
Is there a nice functional way to do this? I know there is an each_with_index method returning an Enumerable, but I couldn’t figure out how to wield it with a filter.
Edit: NVM, JUST solved it after 30 minutes of trying. Here is my method.
indexes = stuff.collect.with_index { |elem, index| index if elem == " "}.
select { |elem| not elem.nil? }
Let me shorten it a bit for you:
The thing is that you can use
Enumerable#compactinstead of doing aselect. Also, I find#mapto be the more popular term, especially when you talk about functional programming, but that’s apples and oranges in the end.