[英]undefined method `chomp' for nil:NilClass (NoMethodError)
[英]`input_data': undefined method `chomp' for nil:NilClass (NoMethodError)
大家好我有以下問題:
輸入 :
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
任何建議如何解決?
gets
的回報nil
,這不可能是chomp
版。 因此,您需要確保在調用chomp
之前處理實際的字符串。 ruby中的一個常見習慣是使用||=
運算符來設置變量,只有它是nil。 所以你會寫:
tries = gets # get input
tries ||= '' # set to empty string if nil
tries.chomp! # remove trailing newline
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.