我如何扭转否定条件并在此红宝石语法中交换IF-ELSE分支

发布于 2025-02-09 02:49:26 字数 679 浏览 1 评论 0原文

VS代码在这条线上显示一条线条,我想知道为什么。 这是代码行:

if answer != ""

它说:

扭转否定条件并交换if-else分支。

在代码片段下面找到下面

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半枫 2025-02-16 02:49:26

转换代码:

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

,这意味着您应该从以下方面

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

当Vs说“倒置否定条件并交换If-else分支” 成为==,因此,如果 branch “分支a” else branch “分支” b“ 交换了。


应用于您的代码,建议这样写:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文