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?

3 Answers 3

9

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

> gather "banana".indices("a"|"b").deepmap: *.take
(1 3 5 0)
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'] }  
4
  • Nice, but the OP said he didn't want to use regex. May 12, 2018 at 4:24
  • @Håkon Hægland is "banana".comb equals to "banana".comb(/./)
    – chenyf
    May 12, 2018 at 5:20
  • Sorry I wasn't thinking. Although the name grep comes from "global regexp" it is not using regex here. 'a' | 'b' is just a junction of two characters. I am not sure about comb, but I see no reason why it should use regex. May 12, 2018 at 5:31
  • 1
    Actuallly, .comb does not use any regexes internally. It just creates an iterator on all graphemes in the string. May 12, 2018 at 7:13
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).

3
  • Which version, do you think, will be the fastest? May 12, 2018 at 8:16
  • 3
    @EugeneBarsky What is fastest today may not be the fastest in the future. It may also be dependent on your particular data. If speed is important to you, I recommend trying the different approaches on your machine with your data (or a representative sample of your data). May 12, 2018 at 11:08
  • @ChristopherBottoms Thanks, I'll try it. May 12, 2018 at 12:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.