Fernando Briano
Fernando Briano

Reputation: 7757

Exception: nil can't be coerced into Fixnum when comparing two Strings

Simple Ruby question but it's driving me crazy. I have a method to compare two strings and return 1 if string one includes string two. The method is in a Module.

This is the code:

  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

While debugging, when I get to the if line, I get nil can't be coerced into Fixnum comparing two Strings. I debugged and printed the string's classes and they're never nil or anything different from String. Any ideas?

UPDATE: I ran unit tests on the method and it works as expected. The problem must be coming from somewhere else, so I'll keep on checking the code out.

Upvotes: 1

Views: 397

Answers (1)

ben
ben

Reputation: 1849

if gsub! does no substitutions, then it returns nil. see here

ruby-1.9.2-p136 :001 > first_string = "nospaces"
 => "nospaces" 
ruby-1.9.2-p136 :002 > first_string.gsub!(/\s+/, "")
 => nil

be sure not to use nil in your if clause

Upvotes: 2

Related Questions