1

I'm trying to use multiple conditions in an IF statement, to see if the number entered was 5, 10, or 15. If the input is not one of these numbers, then it should output an error message.

But even if 5, 10, and 15 are input, it always outputs the error message.

when 3
  print("Enter the discount percentage, must be (5, 10, or 15)")
  dis= gets.to_i
  if (dis != 5 || dis != 10 || dis != 15)
    puts("You entered an invalid discount")
  else
  end
3
  • The correct method to get an integer from the beginning of a string would be to_i, not _i. Commented Feb 11, 2017 at 19:46
  • 1
    p || q is the same as !(!p && !q) (from De Morgan's Law). So your expression is the same as !(dis == 5 && dis == 10 && dis == 15). The expression within the parentheses is obviously false for any value of dis, so !(false) #=> true, causing puts to be executed regardless of the value of dis. Commented Feb 11, 2017 at 20:06
  • Why the rush to select an answer? Commented Feb 11, 2017 at 20:16

4 Answers 4

3

Correct logic for your condition would be

if dis != 5 && dis != 10 && dis != 15

Because you want to print the error if the number is not 5, nor 10, nor 15. A more cool way to write that is

if [5, 10, 15].all? { |i| dis != i }
Sign up to request clarification or add additional context in comments.

3 Comments

or even if [5, 10, 15].none? { |i| dis == i }
Thanks for showing me 2 different ways of writing this and explaining why. very much appreciate it.
My pleasure Sir :)
2

One could useEnumerable#grep:

puts ("You entered an invalid discount") unless [5,10,15].grep(dis).any?

3 Comments

Thanks, haven't seen that one before as i am still real new to this. i will save that one for future use.
@pjs actually without any? it will not work (since empty array is truthy), so thanks for noticing!
@AndreyDeineko with any? you don't need grep, and it should be faster for larger lists because it can short circuit the search.
2
puts ("You entered an invalid discount") unless [5,10,15].include?(dis)

Comments

1

Just another way using regex:

puts "Enter discount, must be 5,10 or 15"
puts gets[/\A1?[05]\n\z/] ? 'Discount applied' : 'Invalid discount'

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.