【发布时间】:2021-05-27 12:53:48
【问题描述】:
我有一个小程序,它接收用户输入的文本,询问要编辑的单词,然后编辑该单词:
puts "Text to search through: "
text = gets.chomp
puts "Word to redact: "
redact = gets.chomp
words = text.split(" ")
words.each do |word|
if word != redact
print "no such word. "
else
print "REDACTED ! "
end
end
但是,我不喜欢输出,因为使用 .each 方法会重复并且看起来不整洁。
Text to search through:
this is my text
Word to redact:
is
no such word. REDACTED ! no such word. no such word.
阻止它为数组的每个元素重复答案并打印“已编辑!”的解决方案是什么?只有一次?
或者当没有要编辑的词时,而不是像这样对每个元素重复答案:
Text to search through:
this is my text
Word to redact:
no
no such word. no such word. no such word. no such word.
只打印一次“No such word”。谢谢。
【问题讨论】:
-
"然后编辑那个词" – 你的代码只打印“REDACTED !”无需实际更改输入。
-
其实你是对的,它并不是我想要它做的事情
-
您可能想看看
gsub!- 如果没有进行任何更改,bang 变体返回nil。