Keshav
Keshav

Reputation: 3

How can I invert the negated condition and swap the if-else branch in this ruby syntax

VS Code is showing a squiggly line on this line and I wonder why. Here is the line of code:

if answer != ""

It says:

Invert the negated condition and swap the if-else branches.

Find below the code snippet

def coach_answer(your_message)
  if your_message.downcase == "i am going to work right now!"
    ""
  elsif your_message.end_with?("?")
    "Silly question, get dressed and go to work!"
  else
    "I don't care, get dressed and go to work!"
  end
end

def coach_answer_enhanced(your_message)
  answer = coach_answer(your_message)
  if answer != ""
    if your_message.upcase == your_message
      "I can feel your motivation! #{answer}"
    else
      answer
    end
  else
    ""
  end
end

Upvotes: 0

Views: 195

Answers (1)

Stefan
Stefan

Reputation: 114208

When VS says "Invert the negated condition and swap the if-else branches" it means that you should convert your code from:

if obj != expression
  # branch A
else
  # branch B
end

to:

if obj == expression
  # branch B
else
  # branch A
end

The negated condition != was inverted to become == and accordingly, the if branch "branch A" and the else branch "branch B" were swapped.


Applied to your code, it suggests to write it this way:

def coach_answer_enhanced(your_message)
  answer = coach_answer(your_message)
  if answer == ""
    ""
  else
    if your_message.upcase == your_message
      "I can feel your motivation! #{answer}"
    else
      answer
    end
  end
end

Upvotes: 2

Related Questions