Ruby 中三元运算符的布尔校验



有这样的代码

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

尝试写string.start_with? 'a' ? 'true' : 'false'给我警告 warning: string literal in condition并且无法按预期工作。这不是关于给定警告的问题,而是关于Ruby中三元运算符的正确语法的问题问题:是否可以使用三元运算符重写上面的代码?

为什么不只是:

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

在您的情况下,ruby 按下一个顺序执行代码:

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

最新更新