重复代码一次而不是每个元素 - .each 方法 - Ruby
repeat the code once and not to every element - .each method - Ruby
我有这个小程序,它接受用户输入的文本,询问要编辑哪个词,然后编辑那个词:
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.
只打印一次“没有这样的词”。谢谢
您可以使用 Array#include? 方法来检查是否包含 redact:
if words.include?(redact)
print "REDACTED !"
else
print "no such word."
end
我有这个小程序,它接受用户输入的文本,询问要编辑哪个词,然后编辑那个词:
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.
只打印一次“没有这样的词”。谢谢
您可以使用 Array#include? 方法来检查是否包含 redact:
if words.include?(redact)
print "REDACTED !"
else
print "no such word."
end