错误的参数数量(至少1)

时间:2013-09-03 07:45:42

标签: ruby iterator

作为红宝石挑战训练的一部分,我被要求创建一个方法子串(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")

任何帮助非常感谢!

4 个答案:

答案 0 :(得分: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")

答案 1 :(得分: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

答案 2 :(得分: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"]

答案 3 :(得分: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() } }