I am trying to create a program where a user enters four numbers using regular expressions . If one of those numbers is 13 then the numbers to the left do not count toward the sum. My problem is creating an exception where none of the numbers equal 13. I cant seem to find a regular expression for my exception
puts "enter a number then hit enter four times"
number1 = STDIN.gets
number2 = STDIN.gets
number3 = STDIN.gets
number4 = STDIN.gets
if number1 =~ /13/ then
puts number2.to_i + number3.to_i + number4.to_i
end
if number2 =~/13/ then
puts number3.to_i + number4.to_i
end
if number3 =~/13/ then
puts number4.to_i
if number4 =~/13/ then
puts "0"
end
if number1 != 13 or number2 != 13 or number3 != 13 or number4 != 13
puts number1.to_i + number2.to_i + number3.to_i + number4.to_i
end
end
If you want to use regular expressions, it should be mentioned that the following logic will yield true for more than just 13. It will also match 413, 131, 941771341, …
Changing it to
if number =~ /^13$/ thenwould be more accurate, but not as good as using toto_i.The other line in question…
…doesn’t work as expected because you are comparing a string to a number, and the logic join should be
and. Comparing it to “13” won’t work either, since it is actually “13\n”. You can usenumber1.to_i != 13 and number2.to_i != 13or something likenumber1 !~ /^13$/ and number2 !~ /^13$/ ...You could also figure out where to use anelsestatement in there.I really recommend studying the other answers though. They are far more elegant and Rubyesque.