3

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?

1
  • A reminder to readers that Ruby has three ways of testing for equality: puts "#{5 == 5.0}, #{5.eql?(5.0)}, #{5.equal?(5.0)}" # => true false false. true because the values are the same, false #1 because the values are different types, even though they are (=) equal, false #2 because the values have different object_id's. Commented Jan 30, 2014 at 20:56

2 Answers 2

10

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?("?") 
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.