Cannon Moyer
Cannon Moyer

Reputation: 3164

|| in Ruby - Unexpected Keyword End

I figure I am missing something trivial but for some reason this code doesn't work and gives an unexpected keyword end error:

if @quote.user.email.include? "test" || @quote.user.email.include? "test2"
    email = ""
else
    email = @quote.user.email
end

However, this works if I wrap each statement in parenthesis like this.

if (@quote.user.email.include? "test") || (@quote.user.email.include? "test2")
    email = ""
else
    email = @quote.user.email
end

Why is this the case?

Upvotes: 1

Views: 178

Answers (1)

PhilVarg
PhilVarg

Reputation: 4811

the compiler cant tell what you're trying to do.

@quote.user.email.include? "test" || @quote.user.email.include? "test2"

is very ambiguous, and so the compiler tries to figure out what this means.

@quote.user.email.include?("test") || @quote.user.email.include?("test2")
@quote.user.email.include?("test" || @quote.user.email.include?) "test2"
@quote.user.email.include?("test" || @quote.user.email.include?("test2"))
(@quote.user.email.include? "test") || (@quote.user.email.include? "test2")

in this case, the compiler grants preference to the or operator, which is the second case. this is not valid syntax, and consequently throws an error

leaving off parens (seattle style syntax) is convenient, but sometimes it gets too ambiguous, and you need to use them

i'd recommend adding parens to the method arguments

@quote.user.email.include?("test") || @quote.user.email.include?("test2")

Upvotes: 4

Related Questions