如何在Ruby中将句子分成多个部分

ale*_*our 2 ruby string split

我想拆分一个主字符串,并用Ruby中获得的单词创建多个字符串.

str = "one two three four five"
Run Code Online (Sandbox Code Playgroud)

我想在一个字符串数组中创建所有这些可能性:

"one"
"one two"
"one two three"
"one two three four" 
"one two three four five" 
Run Code Online (Sandbox Code Playgroud)

但是也:

"two three four five"
"three four five"
"four five"
"five"
Run Code Online (Sandbox Code Playgroud)

理想情况下我也会在里面获取字符串,但不是必需的:

"two three four"
"two three"
"three four"
Run Code Online (Sandbox Code Playgroud)

我尝试了很多东西,但很难有最好的方法来做到这一点.

例如,我尝试使用each_slice:

words = string.split(" ")
        number_of_words = words.length
        max_number_of_slices = number_of_words
        array_of_strings_to_match = []
        number_of_slices = 1
        while (number_of_slices <= max_number_of_slices)
          array = words.each_slice(number_of_slices).map do |a| a.join ' ' end
          array.each do |w| array_of_strings_to_match << w end
          number_of_slices = number_of_slices + 1
        end
Run Code Online (Sandbox Code Playgroud)

但这不是好方法.

欢迎任何想法.:-)

这个问题是从一点点不同的这一个,因为我需要分开单词的句子,而不是由一串字母(即使它是完全一样的).

Ale*_*kin 9

str = "one two three four five".split
1.upto(str.size).flat_map { |i| str.each_cons(i).to_a }

#? [["one"], ["two"], ["three"], ["four"], ["five"],
#   ["one", "two"], ["two", "three"], ["three", "four"], ["four", "five"],
#   ["one", "two", "three"], ["two", "three", "four"], ["three", "four", "five"],
#   ["one", "two", "three", "four"], ["two", "three", "four", "five"], 
#   ["one", "two", "three", "four", "five"]]
Run Code Online (Sandbox Code Playgroud)