puts "Enter first day" a = gets.chomp.to_i puts "Enter second day" b = gets.chomp.to_i if (a == "monday") n1 = 1 end ... if (a == "sunday") n1 = 7 end if (b == "monday") n2 = 1 end ... end if (b == "sunday") n2 = 7 end 

line 51:

 dif = n2 - n1 if (dif < -1) puts "YES" else puts "NO" end 

The command line goes:

 in line 51 in '<main>': undefined method '-' for nill:NilClass (NoMethodError) 

Says that n1 and n2 do not exist.

How to fix the error?

    1 answer 1

     a = gets.chomp.to_i # ^^^^^ 

    You convert the entered string to a number ...

     if (a == "monday") 

    ... and then compare the number with the string .

    Ruby has strong typing . These are different data types, and the equality operator for strings and numbers on different types always returns false . Your condition will simply never be fulfilled.

    Track which type has each value in your program and make sure that there is what you expect.


    You may be interested in why there was no NameError , if in the end nothing came of the variable. Where did nil come from. There is a very significant case, demonstrating where this behavior comes from:

     x = x # ...когда `x` не определён # => nil 

    Ruby syntax is designed in such a way that local variables in the code can be seen in advance. The interpreter initializes all local variables of a piece of code in nil prior to its execution.

    It is in this line that the interpreter sees that x local variable and assignment occurs in it. So when the performance starts, there is already nil .

    • an exhaustive answer (-: - Vetal4eg