【问题标题】:Lint error "Literal '+' appeared as a condition" when using ternary if使用三元 if 时出现 Lint 错误“文字 '+' 作为条件出现”
【发布时间】:2018-06-17 20:23:48
【问题描述】:

我有一些代码。如果存在,它应该从字符串中删除尾随 +

def remove_prefix(number)
  number.start_with? '+' ? number[1..-1] : number
end

但它并没有按预期工作——它只是返回false

remove_prefix('123')  #=> false
remove_prefix('+123') #=> false

Rubocop 显示此错误:

Lint/LiteralAsCondition:文字“+”作为条件出现。

我做错了什么?

【问题讨论】:

  • 你测试代码了吗?
  • 是的......我的方法返回布尔值,但我期望字符串值。
  • 仅供参考:String#delete_prefix

标签: ruby rubocop


【解决方案1】:

不好:number.start_with? '+' ? number[1..-1] : number
好:number.start_with?('+') ? number[1..-1] : number

【讨论】:

  • ...因为前者相当于number.start_with?('+' ? number[1..-1] : number)。其中+ 是条件?: 中的文字。所以 Rubocop 在想,你已经知道它是真实的,所以你不妨写 number[1..-1] 而不是 '+' ? number[1..-1] : number。显然,由于没有括号的语法,首先你有错误的条件。
  • @SergeyBlohin 您可能想添加一些关于 为什么 前者是“坏”而后者是“好”的解释(参见 Amadan 的评论)。关于 Rubocop 警告和预期结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 2014-01-12
  • 2016-09-14
  • 2019-09-11
  • 1970-01-01
相关资源
最近更新 更多