嘿,我刚刚开始在codeacademy学习Ruby,而且我遇到了一个我无法接受的可选挑战练习。该程序采用用户定义的字符串和"编辑"用户想要的词语"编辑"。正如您所看到的,它将字符串转换为数组,然后循环遍历数组中的每个值(也就是单个单词),并尝试将原始字符串的值与用户想要的字符串交叉检查"编辑&# 34 ;.最初的问题是让它编辑一个变量,挑战是让多个单词被编辑。我的问题是,当它通过检查循环时,它会错误地返回值。我理解什么是错误的,循环必须不止一次地交叉检查值,并且当它不能' =='它一直打印出来,但是有办法解决这个问题吗?或者有更好的角度来解决这个问题吗?
puts "Give me what you've got"
text = gets.chomp
text.downcase!
puts "What words do you wish to redact"
redact = gets.chomp
redact.downcase!
bye_words = redact.split(" ")
words = text.split(" ")
words.each do |single_word|
bye_words.each do |word_in_question|
if word_in_question == single_word
print "REDACTED "
else
print single_word + " "
end
end
end
答案 0 :(得分:0)
这样的事情怎么样?您不必遍历两个不同的集合:
puts "Give me what you've got"
text = gets.chomp
text.downcase!
puts "What words do you wish to redact"
redact = gets.chomp
redact.downcase!
bye_words = redact.split(" ")
words = text.split(" ")
ouput_words = []
words.each do |single_word|
if bye_words.include?(single_word)
ouput_words << "REDACTED"
else
ouput_words << single_word
end
end
print ouput_words.join(" ") + "\n"
答案 1 :(得分:0)
也许只使用include?而不是另一个循环:
puts "Give me what you've got"
text = gets.chomp
text.downcase!
puts "What words do you wish to redact"
redact = gets.chomp
redact.downcase!
bye_words = redact.split(" ")
words = text.split(" ")
words.each do |single_word|
if bye_words.include? single_word
print "REDACTED "
else
print single_word + " "
end
end
甚至是gsub,但也许是在作弊......?
答案 2 :(得分:0)
获得(几乎)所需内容的最快方法是使用-
:
puts "Give me what you've got"
text = gets.chomp
text.downcase!
puts "What words do you wish to redact"
redact = gets.chomp
redact.downcase!
bye_words = redact.split(" ")
words = text.split(" ")
puts (words - bye_words).join(' ')
问题是编辑后的文字只会从文字中移除('REDACTED'
不会被添加)。
要填写该要求,您需要查找included?
中的每个单词是bye_words
。如何改善其他人的建议是将bye_words
列表变为Set
。
require 'set'
puts "Give me what you've got"
text = gets.chomp
text.downcase!
puts "What words do you wish to redact"
redact = gets.chomp
redact.downcase!
bye_words = Set.new(redact.split(" "))
words = text.split(" ")
puts words.map { |word| bye_words.include?(word) ? 'REDACTED':word }.join(' ')