Reputation: 33
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
Upvotes: 2
Views: 167
Reputation: 1716
It's a boolean condtion that causes this to happen.
Boolean values are either a 0
or 1
.
&&
is used BOTH variables must be 1
to be true
. ||
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)
Nifty.
Upvotes: 0
Reputation: 47472
Following should work
if x == redact || x == redact_another
print "REDACTED "
else
print x + " "
end
OR
print [redact, redact_another].include?(x) ? "REDACTED " : x + " "
Upvotes: 1