What is the best way to split a string to get all the substrings by Ruby?

def split_word s
  (0..s.length).inject([]){|ai,i|
    (1..s.length - i).inject(ai){|aj,j|
      aj << s[i,j]
    }
  }.uniq
end

And you can also consider using Set instead of Array for the result.

PS: Here’s another idea, based on array product:

def split_word s
  indices = (0...s.length).to_a
  indices.product(indices).reject{|i,j| i > j}.map{|i,j| s[i..j]}.uniq
end

Leave a Comment