【发布时间】:2014-12-12 08:55:46
【问题描述】:
我正在尝试用我的代码做一些事情,但我对如何与数组的元素进行交互感到困惑。这段代码的重点是将字符串作为输入并编辑某些单词。
我的目标是:
让我的程序编辑多个单词。
创建一个新的编辑字符串并将其保存为变量,而不是仅仅将其打印到控制台
我已经使用 cmets 概述了我的逻辑(cmets 中也有几个问题)。
puts "Write something: "
text = gets.chomp
puts "Redact some words: "
redact = gets.chomp
words = text.split(" ") #Turns string into array of words
redact_words = text.split(" ")
words.each do |word| #Iterates through each component of array [words] and permanently
word.downcase! #makes the placeholder (word) lower case.
end #Apparently this works also: words.map!(&:downcase) to make it
#undercase but I'm not sure why? What is .map? What is &:?
words.each do |word|
if redact_words.include?(word) #iterates through each component of array [redact_words] and
#checks if it includes the placeholder (word). If it does,
text.gsub!("#{word}","REDACTED") # it permanently globally substitutes the string of placeholder
#(word) with the string "REDACTED".
else puts "No redactable word(s) found"
end
end
puts text
我的代码运行得不是很好,因为它没有看到大小写。
如果您输入“Hello hello Okay OK”作为第一个输入。并且“你好,好吧”作为第二个输入。你会得到“Hello REDACTED Okay REDACTED”作为输出。
我 认为 是因为它打印修改后的字符串文本而不是数组 [words](这是我想要的,因为我希望将编辑后的字符串保存到变量中)。有没有其他方法可以做到这一点?
另外,除了使用 regexp(正则表达式)之外,有没有办法进行我所做的替换?
【问题讨论】:
-
应该是
words = text.split(" ")和redact_words = redact.split(" ")。这是一个错字还是您在实际代码中犯了错误? -
那是一个错字。但是由于某种原因,它仍然得到了相同的结果...... O_O
-
我一直使用 repl.it/languages/Ruby 作为我的 Ruby 解释器。