micgeronimo micgeronimo - 1 year ago 92
Ruby Question

boolean check with ternary operator in Ruby

Having such code

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

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
Is it possible to rewrite above code using ternary operator?

Answer Source

Why not just:

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

In your case ruby executes code in the next order:

string.start_with? ('a' ? true : false)
# expected
string.start_with?('a') ? 'true' : 'false'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download