Reputation: 173
So, I'm running into this issue wherein I want to have three conditions be checked before the routine continues, but it keeps throwing up syntax errors saying it didn't expect the multiple conditions. Now, I know I've seen other people use lines such as:
if x > 100 && x % 2 == 1
#Do something
end
But, for whatever reason, this line:
if (letters.eql? letters.upcase && dash.eql? '-' && numbers.to_i.to_s.eql? numbers)
is throwing up tons of errors. Is it something to do with '.eql?' or is it something extraneous about Ruby that I haven't encountered yet?
Here's the rest of the code for reference:
print "Enter license plate: ";
input = gets.strip;
if input.length == 8
letters = input[0,2];
dash = input[3];
numbers = input[4,7];
if (letters.eql? letters.upcase && dash.eql? '-' && numbers.to_i.to_s.eql? numbers)
puts "#{input} is a valid license plate."
else
print "All valid license plates are three (3) uppercase letters, followed by a dash (-), followed by four (4) digits";
end
else
print "All valid license plates are 8 characters long.";
end
Also, these are the errors:
LicensePlate.rb:7: syntax error, unexpected tSTRING_BEG, expecting ')'
...? letters.upcase && dash.eql? '-' && numbers.to_i.to_s.eql? ...
... ^
LicensePlate.rb:7: syntax error, unexpected tIDENTIFIER, expecting ')'
... numbers.to_i.to_s.eql? numbers)
...
Upvotes: 11
Views: 48061
Reputation: 114138
In addition to the other answers - consider using a regular expression to check the format:
print "Enter license plate: "
input = gets.chomp
if input.length != 8
puts "All valid license plates are 8 characters long."
elsif input !~ /^[A-Z]{3}-\d{4}$/
print "All valid license plates are three (3) uppercase letters, followed by a dash (-), followed by four (4) digits"
else
puts "#{input} is a valid license plate."
end
Upvotes: 1
Reputation: 351
This also works:
letters.eql? letters.upcase and dash.eql? '-' and numbers.to_i.to_s.eql? numbers
I believe this is due to operator precedence since this also works:
(letters.eql? letters.upcase) && (dash.eql? '-') && (numbers.to_i.to_s.eql? numbers)
Ruby seem to try and evaluate your condition prematurely.
EDIT: Just saw that Lurker was mentioning precedence previously.
Upvotes: 4
Reputation: 1318
This should do it:
if letters.eql?(letters.upcase) && dash.eql?('-') && numbers.to_i.to_s.eql?(numbers)
You can still wrap the entire conditional in parenthesis if you would like, but with Ruby (unlike JavaScript), you don't need to.
Upvotes: 10
Reputation: 899
Think you're just missing some parens - try this:
if (letters.eql?(letters.upcase) && dash.eql?('-') && numbers.to_i.to_s.eql?(numbers))
Upvotes: 6