21

Using the first bit of code below I receive two warning messages: warning: string literal in condition x2

if input == "N" || "n"
  #do this
else input == "L" || "l"
  #do this

as opposed to using this which results in no warnings

if input == "N" || input == "n"
  #do this
else input == "L" || input == "l"
  #do this

I'm wondering why the first bit of code results in a warning, and the downside of using it.

1
  • 5
    input == "N" || "n" means (input == "N") || "n" - ruby is being helpful and saying "you're doing it wrong" Jan 1, 2014 at 10:43

4 Answers 4

32

change input == "N" || "n"

to

input == "N" || input == "n"

You must also use else if instead of else

The warning is saying that instead of a boolean or test, you have a string literal, ' n', which always evaluates to true.

1
  • 3
    Shouldn't it be elsif?
    – Cyoce
    Feb 26, 2017 at 2:13
1

I have the same error as you but a different problem, found this through Google might as well post my solution for the next Googler.

I had a typo in my code which also gives the same warning:

if input =! "N"

of course the right way:

if input != "N"
1
  • I had !== which gave me this error because of one too many = Oct 30, 2017 at 0:57
1

When you are writing input == "N" || "n"( internally Ruby sees it (input == "N") || "n"), it means "n" string object is always a truth value. Because in Ruby every object is true, except nil and false. Ruby interpreter is warned you there is not point to put ever true value is conditional checking. Conditional check statement always expect equality/un-equality test kind of expression. Now you can go ahead this way or re-think again. if input == "N" || input == "n" is not throwing any warning, as it obeys the norm of conditional test.

else input == "L" || "l" is wrong, as else statement don't expect any conditional test expression. Change it to elseif input == "L" || "l"

1

I was also looking for the answer to this question, and thanks to a friend found a few other solutions.

1) Change the case for the input so you only have to make one test:

if input.downcase == "n"

2) Use a more sophisticated check on the input data:

if %w{n N}.include?(input)     or
if ['n', 'N'].include?(input)

The second one allows for far more flexibility with your checking , especially if there are groups of entry you are looking for.

Hope what I found helps others.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.