拆分字符串以获取Ruby的所有子字符串的最佳方法是什么?

例如,单词“stack”,我想得到一个像这样的数组:

['s', 'st', 'sta', ... 'stack', 't', 'ta', ... , 'c', 'ck', 'k'] 

我是通过这样的代码做到的:

 def split_word(str) result = [] chas = str.split("") len = chas.size (0..len-1).each do |i| (i..len-1).each do |j| result.push(chas[i..j].join) end end result.uniq end 

那有更好,更干净的方法吗? 谢谢。

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

您还可以考虑使用Set而不是Array来获得结果。

PS:这是基于arrays产品的另一个想法:

 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 

我写道:

 def split_word(s) 0.upto(s.length - 1).flat_map do |start| 1.upto(s.length - start).map do |length| s[start, length] end end.uniq end groups = split_word("stack") # ["s", "st", "sta", "stac", "stack", "t", "ta", "tac", "tack", "a", "ac", "ack", "c", "ck", "k"] 

使用map (function)而不是模式init empty + each + append + return (命令式)通常更清晰,更紧凑。

不要这么认为。

这是我的尝试版本:

 def split_word(str) length = str.length - 1 [].tap do |result| 0.upto(length) do |i| length.downto(i) do |j| substring = str[i..j] result << substring unless result.include?(substring) end end end end 
 def substrings(str) output = [] (0...str.length).each do |i| (i...str.length).each do |j| output << str[i..j] end end output end 

这只是你的方法的一个清理版本,它使用较少的步骤=)

 def substrings(str) (0...str.length).map do |i| (i...str.length).each { |j| str[i..j]} end end 

只是另一种方式,这对我来说更清晰。

稍后,但这是我重新格式化你的代码所得到的。

 def substrings(string) siz = string.length answer = [] (0..siz-1).each do |n| (n..siz-1).each do |i| answer << string[n..i] end end answer end