Question

This code works as expected:

if phrase.last.eql? "?" ? true : false
  true
else 
  false
end

but this code using the Ruby ternary operator:

phrase.last.eql? "?" ? true : false

gives the following error:

warning: string literal in condition

Do I need to escape the "?" somehow?

Was it helpful?

Solution

Without parentheses, ruby is interpreting it as

phrase.last.eql?( "?" ? true : false )

which explains the message "warning: string literal in condition".

To fix this, use parentheses on the parameter:

phrase.last.eql?("?") ? true : false

Of course, in this case using the ternary operator is redundant since this is the same as simply

phrase.last.eql?("?")

OTHER TIPS

write as below :

phrase.last.eql?("?") ? true : false

Example :

2.0.0-p0 :023 > x = "a"
 => "a" 
2.0.0-p0 :024 > x.eql? "?" ? 1 : 2
(irb):24: warning: string literal in condition
 => false 
2.0.0-p0 :025 > x.eql?("?") ? 1 : 2
 => 2 
2.0.0-p0 :026 > 

Otherwise x.eql? "?" ? 1 : 2 is interpreted as x.eql?("?" ? 1 : 2). Now in Ruby except nil and false all objects are true. Thus here "?" ? 1 : 2, "?" always will be true, so you got a warning for it. Putting a ever truth value in the conditional test, has no meaning, and the same warning is being thrown to you fro Ruby interpreter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top