本文介绍了在Ruby中,为什么&&在||期间工作不在我的示例代码中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的示例代码中,我试图用'redact'或'redact_again'替换'text'中的任何单词.由于这是一个要么/或方案,我想将使用||.事实证明&&确实有效.如果两者都匹配,则将其正确替换为已编辑"一词.如果找不到匹配项,它将按原样重新打印文本".我只想了解为什么在任何情况下都不能使用||?

In my sample code, I'm trying to replace any words in 'text' that match with either 'redact' or 'redact_again'. Since it's an either/or scenario, I thought || would be used. It turns out that && actually works. If both or either one match, it replaces them with the word "Redacted" properly. If it doesn't find a match, it just reprints the 'text' as it should. I just want to understand why using || doesn't work in an either/or scenario?

puts "Tell me a sentence"
text = gets.chomp.downcase
puts "Redact this word: "
redact = gets.chomp.downcase
puts "And redact another word: "
redact_another = gets.chomp.downcase

words = text.split(" ")
words.each do |x|
 if x != redact && x != redact_another
 print x + " "
 else
 print "REDACTED "
 end
end

推荐答案

它是 boolean 导致这种情况发生的条件.

It's a boolean condtion that causes this to happen.

布尔值是01.

  • 使用&&时,两个变量都必须为1才能为true.
  • 使用||时,EITHER变量必须为1才能为true.
  • When && is used BOTH variables must be 1 to be true.
  • When || is used EITHER variables must be 1 to be true.

反转逻辑意味着以下两个语句在逻辑上是正确的:

Inverting the logic implies that the following two statements are logically correct:

(x == redact || x == redact_another) == (if x != redact && x != redact_another)

好看.

这篇关于在Ruby中,为什么&&在||期间工作不在我的示例代码中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 03:23