作为ruby挑战训练的一部分,我被要求创建一个方法子字符串(string),它将获取一个字符串,并返回一个包含所有子字符串的数组。
即
substrings("cat") #=> ["c", "ca", "cat", "a", "at", "t"]
为此,我尝试创建以下方法,但当我运行它时,会得到错误
ArgumentError: wrong number of arguments (at least 1)
def substrings(string)
i = 0
answer_arr = []
while i < string.count
for val in i...string.count do
substring = string.(i..val)
unless answer_arr.include?(substring)
answer_arr << substring
end
end
i+=1
end
answer_arr
end
substrings("stepan")
非常感谢您的帮助!
最佳答案
def substrings(string)
(0...string.length).flat_map { |i|
(i...string.length).map {
|j| string[i..j]
}
}
end
检查:
>> substrings('cat')
=> ["c", "ca", "cat", "a", "at", "t"]