`input_data':nil的未定义方法`chomp':NilClass(NoMethodError)

use*_*076 2 ruby

大家好我有以下问题:

输入:
2
ababaa
aa

输出:
11
3

说明:
对于第一种情况,字符串的后缀是"ababaa","babaa","abaa","baa","aa"和"a".每个字符串与字符串"ababaa"的相似性分别为6,0,3,0,1,1.因此答案是6 + 0 + 3 + 0 + 1 + 1 = 11.

对于第二种情况,答案是2 + 1 = 3.

这部分有效,但我的代码应该通过的一些测试没有.

这是我的代码

def input_data
#STDIN.flush
tries = gets.chomp
end

strings=[];
tries = input_data until (tries =~ /^[1-9]$/)
tries = tries.to_i
strings << input_data until (strings.count == tries)

strings.map do |x|
values = 0
current = x.chars.to_a
(0..x.length-1).map do |possition| 
    current_suffix = x[possition..-1].chars.to_a
    (0..current_suffix.length-1).map do |number|
        if (current_suffix[0] != current[0])
            break
        end

        if ( current_suffix[number] == current[number] )
            values = values+1
        end
    end 
  end

  if (values != 0)
    puts values
  end
end
Run Code Online (Sandbox Code Playgroud)

任何建议如何解决?

Pat*_*ity 9

gets返回nil,不能chomp编辑.因此,您需要确保在调用之前处理实际的字符串chomp.ruby中的一个常见习惯是使用||=运算符来设置变量,只有它是nil.所以你会写:

tries = gets        # get input
tries ||= ''        # set to empty string if nil
tries.chomp!        # remove trailing newline  
Run Code Online (Sandbox Code Playgroud)