-3

I have some code. It should remove a trailing + from a string if present:

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

But it doesn't work as expected – it just returns false:

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

Rubocop shows this error:

Lint/LiteralAsCondition: Literal '+' appeared as a condition.

What am I doing wrong?

Stefan
  • 109,145
  • 14
  • 143
  • 218
Sergey Blohin
  • 600
  • 1
  • 4
  • 31

1 Answers1

3

bad: number.start_with? '+' ? number[1..-1] : number
good: number.start_with?('+') ? number[1..-1] : number

Sergey Blohin
  • 600
  • 1
  • 4
  • 31
  • 3
    ...because the former is equivalent to `number.start_with?('+' ? number[1..-1] : number)`. Where `+` is a literal in a conditional `?:`. So Rubocop is thinking, you already know it's truthy, so you might as well have written `number[1..-1]` instead `'+' ? number[1..-1] : number`. Obviously, you have the wrong conditional in the first place, due to parenthesis-less syntax. – Amadan Jun 18 '18 at 01:06
  • @SergeyBlohin you might want to add some explanation as to _why_ the former is "bad" and the latter is "good" (see Amadan's comment). Both, in regard to the Rubocop warning and the expected result. – Stefan Jun 18 '18 at 10:07