2012-12-02 46 views
2

好傢伙,我有以下問題:`input_data ':未定義的方法`格格' 的零:NilClass(NoMethodError)

INPUT
ababaa
AA

OUTPUT

說明:
對於第一種情況,字符串的後綴是「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 

任何建議如何解決它?

回答

8

gets返回nil,其不能是chomp ed。因此,在調用chomp之前,您需要確保您使用實際的字符串。紅寶石常見的用法是使用||=運算符來設置一個變量,只有當它爲零時。所以你會寫:

tries = gets  # get input 
tries ||= ''  # set to empty string if nil 
tries.chomp!  # remove trailing newline 
相關問題