我要求输入,然后询问用户想要编辑哪些单词。然后尝试打印带有redacted字样的字符串。
puts "Input please"
text = gets.chomp
puts "What would you like redacted, sir? Type DONE when nothing else to redact"
redact = Array.new
answer = gets.chomp
until answer.downcase == "done"
redact << answer.downcase
answer = gets.chomp
end
words = text.split (" ")
words.each do |word|
if word.include? (# An array to redact)
# Replace words here
print "REDACTED "
else
print word + " "
end
end
答案 0 :(得分:0)
你可以这样做。
words.map {|word| redact.include?(word) ? 'REDACTED' : word}
这会迭代words
数组中的每个元素,并查看该元素是否在redact
数组中。如果是,则将其值更改为'REDACT'
,否则保持单词相同。
请注意,这将创建一个新数组,因此您可能希望将其分配给新变量。如果您想编辑words
数组,可以使用map!
函数。
boolean ? true_path : false_path
被称为三元,它只是
的缩写if boolean
true_path
else
false_path
end
答案 1 :(得分:0)
只是单向解决!!
words.each do |word|
if redact.include?(word)
#IF THE ARRAY REDACT INCLUDES VARIABLE WORD, PRINT REDACT
print "REDACTED "
else print word + " "
end
end