Ruby - Using multiple conditions on a single line

Jeffrey Green picture Jeffrey Green · Dec 14, 2015 · Viewed 27.1k times · Source

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)
...

Answer

Ryan Rebo picture Ryan Rebo · Dec 14, 2015

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.