micgeronimo micgeronimo - 4 months ago 17
Ruby Question

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?

Answer

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'