Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby If Elsif Else block syntax

What's wrong with this block?

if item.nil?
   found = true
elsif item[:name] == name && item[:category] == category
   found = true
else
   i++
end

When I do syntax checking, I get

syntax error, unexpected keyword_end

but if I delete end then I get

syntax error, unexpected end-of-input
like image 395
Omar Darwish Avatar asked Nov 27 '25 10:11

Omar Darwish


1 Answers

The problem is here:

i++

Ruby doesn't have a ++ operator. What you want is this:

i += 1

I believe the reason for that specific error is that Ruby is interpreting the second + as a unary + operator, i.e. the "positive number sign" (because it's the only thing that makes sense in that context), and so expects the next token to be a number, e.g. (parentheses for clarity):

i + (+5)

...but the next token is end, ergo the syntax error.

Or something else that responds to the +@ method.

like image 93
Jordan Running Avatar answered Nov 30 '25 05:11

Jordan Running



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!