我想拆分一个主字符串,并用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略有不同,因为我需要分割一个单词的句子,而不是一个字母的字符串(即使它完全相同)。
答案 0 :(得分: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"]]
答案 1 :(得分:1)
基于this answer的修改版本:
def split_words(string)
words = string.split
(0..words.length).inject([]) do |ai,i|
(1..words.length - i).inject(ai) { |aj,j| aj << words[i,j] }
end.map { |words| words.join(' ') }.uniq
end
用法
str = "one two three four five"
split_words(str)
#=> ["one",
# "one two",
# "one two three",
# "one two three four",
# "one two three four five",
# "two",
# "two three",
# "two three four",
# "two three four five",
# "three",
# "three four",
# "three four five",
# "four",
# "four five",
# "five"]