【发布时间】:2017-11-17 09:55:25
【问题描述】:
我想拆分一个主字符串,并用在 Ruby 中获得的单词创建多个字符串。
str = "one two three four five"
我想在一个字符串数组中创建所有这些可能性:
"one"
"one two"
"one two three"
"one two three four"
"one two three four five"
还有:
"two three four five"
"three four five"
"four five"
"five"
理想情况下,我也会获得里面的字符串,但不是必需的:
"two three four"
"two three"
"three four"
我尝试了很多东西,但很难找到最好的方法。
例如,我尝试使用 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
但这不是好方法。
欢迎任何想法。 :-)
这个问题和this one有点不一样,因为我需要的是一个单词的句子,而不是一个字母的字符串(即使完全一样)。
【问题讨论】:
-
如果我对提议的 dup 运行解决方案,将其称为
split_word(str.split),我相信这会提供您想要的输出