简单的Ruby问题,但它让我发疯。我有一个比较两个字符串的方法,如果字符串1包含字符串2,则返回1。该方法在模块中。
这是代码:
def self.check_similarity first_string, second_string
first_string.gsub!(/\s+/, "")
first_string.downcase!
second_string.gsub!(/\s+/, "")
second_string.downcase!
if first_string.include? second_string
return 1
end
end
在调试时,当我到达if
行时,我得到nil can't be coerced into Fixnum comparing two Strings
。我调试并打印了字符串的类,它们永远不会是字符串或与String有什么不同。有什么想法吗?
UPDATE:我对该方法进行了单元测试,并且按预期工作。问题必须来自其他地方,所以我会继续检查代码。
答案 0 :(得分:2)
如果是gsub!没有替换,然后它返回nil。见here
ruby-1.9.2-p136 :001 > first_string = "nospaces"
=> "nospaces"
ruby-1.9.2-p136 :002 > first_string.gsub!(/\s+/, "")
=> nil
请确保不要在if子句中使用nil