1

作为 ruby​​ 挑战训练的一部分,我被要求创建一个方法 substrings(string),它将接受一个字符串,并返回一个包含所有子字符串的数组。

IE

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")

非常感谢任何帮助!

4

4 回答 4

4

count 是不正确的使用方法。它应该是长度

def substrings(string)

    i = 0 
    answer_arr = []

    while i < string.length 
        for val in i...string.length do 
            substring = string[i..val]
            unless answer_arr.include?(substring)
                answer_arr << substring
            end
        end
        i+=1
    end

    answer_arr
end

substrings("stepan")
于 2013-09-03T07:50:33.620 回答
3

较新的 Ruby 版本具有Array#repeated_combination

str = 'cat'
(0...str.length).to_a.repeated_combination(2).map { |a, b| str[a..b] }
#=> ["c", "ca", "cat", "a", "at", "t"]

解释:

此解决方案基于子字符串范围数组:

                # 0 1 2 (indices)
ranges = [0..0, # c
          0..1, # c a
          0..2, # c a t
          1..1, #   a
          1..2, #   a t
          2..2] #     t

上面的数组可以很容易地构建repeated_combination

ranges == [0,1,2].repeated_combination(2).map { |a, b| a..b }
#=> true
于 2013-09-03T09:19:42.030 回答
0
a="cats"
b = Array.new
a.chars.each.with_index { |i,j| b << a.chars.combination(j+1).to_a }
b.each{ |i| i.each { |j| puts j.join() } }
于 2013-09-03T08:58:58.800 回答
0
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"]
于 2013-09-03T07:56:44.370 回答