Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Using multiple conditions on a single line

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)
...
like image 763
Jeffrey Green Avatar asked Dec 14 '15 21:12

Jeffrey Green


2 Answers

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.

like image 159
Ryan Rebo Avatar answered Sep 23 '22 18:09

Ryan Rebo


Think you're just missing some parens - try this:

if (letters.eql?(letters.upcase) && dash.eql?('-') && numbers.to_i.to_s.eql?(numbers))

like image 35
Rob Mulholand Avatar answered Sep 22 '22 18:09

Rob Mulholand