我正在制作一个简单的程序,根据所选的单词审查用户输入。
puts "Enter your Text: "
text = gets.chomp.downcase!
puts "Word to censor: "
censor1 = gets.chomp
censor1.downcase!
puts "Second word to censor: "
censor2 = gets.chomp
censor2.downcase!
words = text.split(" ")
words.each do |letter|
if letter == censor1
print "CENSORED "
else
print words + " "
end
end
那么,是否可以设置:'if letter == censor1 and censor 2'?
答案 0 :(得分:2)
如果您询问(低级)censorX
是否包含字符letter
:
censor1+censor2.include?(letter)
如果您询问censorX
&#39}是否包含字符letter
:
censor1.include?(letter) && censor1.include?(letter)
如果您询问所有censorX
个字符串是否等于字符串letter
,那么:
if [censor1, censor2,...].uniq == [letter]
...
end
答案 1 :(得分:2)
您可以在Array#include?
if [censor1, censor2].include?(letter)
代码的简化版本:
puts 'Enter your Text: '
text = gets.chomp.downcase
puts 'Word to censor: '
censor1 = gets.chomp.downcase
puts 'Second word to censor: '
censor2 = gets.chomp.downcase
text.split(' ').each do |word|
if [censor1, censor2].include?(word)
print 'CENSORED '
else
print word + ' '
end
end
更简单,更好的解决方案String#gsub
取代了文本中所有出现的删失字词:
puts 'Enter your Text: '
text = gets.chomp.downcase
puts 'Word to censor: '
censor1 = gets.chomp.downcase
puts 'Second word to censor: '
censor2 = gets.chomp.downcase
[censor1, censor2].each { |c| text.gsub!(c, 'CENSORED') }
puts text