9

I want to find indices for more than one letter in a word. I don't want to use Regexes, because they will slow down the program (which is already slower than I wanted).

> "banana".indices(("a", "b").any)
any((1 3 5), (0))

How can I instead get 0, 1, 3, 5?

Eugene Barsky
  • 5,780
  • 3
  • 17
  • 40

3 Answers3

9

I would go for something like this (in the REPL):

> gather "banana".indices("a"|"b").deepmap: *.take
(1 3 5 0)
nxadm
  • 2,079
  • 12
  • 17
8
> "banana".comb.grep: 'a' | 'b',:k
(0 1 3 5)

I don't know if comb use regex in this case:

gather for 'banana'.comb.antipairs  {.value.take if .key ∈ ['a','b'] } 

# or
gather 'banana'.comb.antipairs».&{.value.take if .key ∈ ['a','b'] }  
chenyf
  • 5,048
  • 1
  • 12
  • 35
7

My solution would be:

> <a b>.map( { |"banana".indices($_) } ).sort
(0 1 3 5)

Basically, loop over all of the letters you want to look for (<a b>.map) and map those letters to their indices ("banana".indices($_)), then slip the indices found (|) and sort the result (.sort).

Elizabeth Mattijsen
  • 25,654
  • 3
  • 75
  • 105