user1214632
user1214632

Reputation: 1

Ruby include? in an if-statement

Why does this result in a syntax error "syntax error, unexpected keyword_end, expecting $end"?:

if "test".include?"te" || "test".include?"fail"
  puts "true"
end

The following works:

fail = "test".include?"fail"

if "test".include?"te" || fail
  puts "true"
end

Upvotes: 0

Views: 11365

Answers (4)

David Unric
David Unric

Reputation: 7719

Another solution: replace operator "||" with "or" which has lower precedence so you can leave parentheses omitted:

if "test".include?"te" or "test".include?"fail"
  puts "true"
end

Upvotes: 6

knut
knut

Reputation: 27855

You must use a brace around the 2nd parameter.

if "test".include?("te") || "test".include?("fail")
  puts "true"
end

or

if "test".include? "te" || ("test".include? "fail" )
  puts "true"
end

Upvotes: 3

Substantial
Substantial

Reputation: 6682

Use parentheses with those include? arguments.

if "test".include?("te") || "test".include?("fail")
  puts "true"
end

Upvotes: 5

fl00r
fl00r

Reputation: 83680

if "test".include?("te") || "test".include?("fail")
  puts "true"
end

Upvotes: 1

Related Questions