在Ruby中,我需要将一个句子分成子句

A F*_*kly 0 ruby arrays string

鉴于字符串:

"See Spot Run"
Run Code Online (Sandbox Code Playgroud)

我需要返回一个数组:

[ "See", "Spot", "run", "See Spot", "Spot run", "See Spot Run" ]
Run Code Online (Sandbox Code Playgroud)

到目前为止,我有:

term = "The cat sat on the mat"
#=> "The cat sat on the mat" 

arr = term.split(" ")
#=> ["The", "cat", "sat", "on", "the", "mat"] 

arr.length.times.map { |i| (arr.length - i).times.map { |j| arr[j..j+i].join(" ") } }.flatten(1)
#=> ["The", "cat", "sat", "on", "the", "mat", "The cat", "cat sat", "sat on", "on the", "the mat", "The cat sat", "cat sat on", "sat on the", "on the mat", "The cat sat on", "cat sat on the", "sat on the mat", "The cat sat on the", "cat sat on the mat", "The cat sat on the mat"] 
Run Code Online (Sandbox Code Playgroud)

这种情况会发生很多次,所以你能想出一种提高效率的方法吗?

Ste*_*fan 5

each_cons在一个循环中使用:(虽然它不是更快)

arr = %w[The cat sat on the mat]
(1..arr.size).flat_map { |i| arr.each_cons(i).map { |words| words.join(' ') } }
#=> ["The", "cat", "sat", "on", "the", "mat",
#    "The cat", "cat sat", "sat on", "on the", "the mat",
#    "The cat sat", "cat sat on", "sat on the", "on the mat",
#    "The cat sat on", "cat sat on the", "sat on the mat",
#    "The cat sat on the", "cat sat on the mat",
#    "The cat sat on the mat"]
Run Code Online (Sandbox Code Playgroud)