micgeronimo
micgeronimo

Reputation: 2149

boolean check with ternary operator in Ruby

Having such code

def f(string)
     if string.start_with? 'a'
         return true
     else
         return false
     end
end

Trying to write string.start_with? 'a' ? 'true' : 'false' gives me warning warning: string literal in condition and do not work as expected. That is not question about given warning, but rather about correct syntax for ternary operators in Ruby Question: Is it possible to rewrite above code using ternary operator?

Upvotes: 0

Views: 1117

Answers (1)

Sergii K
Sergii K

Reputation: 855

Why not just:

def f(string)
  string.start_with? 'a'
end

In your case ruby executes code in the next order:

string.start_with? ('a' ? true : false)
# expected
string.start_with?('a') ? 'true' : 'false'

Upvotes: 6

Related Questions