【发布时间】:2013-08-24 23:44:34
【问题描述】:
好的, 我正在做 codeacademy ruby 跟踪,但我不知道这个问题。 我现在可以让它工作,但我不明白它为什么工作。 练习说明:
让我们从简单的开始:编写一个遍历单词的 .each 循环并打印出它找到的每个单词。
我已将问题分解为几个步骤,试图了解它为何有效 但我很困惑。 我的问题代码是:
puts "Text to search through: " #ask user for input
text = gets.chomp
#store the user's input into the variable text
puts "Text to be reducted: "
#ask the user for input
redact = gets.chomp
#store the user's input into the variable redact
words = text.split(" ")
=begin
split the user's input into the variable words
store that input into the variable words
=end
words.each do |word|
=begin
creates a placeholder for the user's input
then attach an expression to the input stored in
the variable words one at a time. The variable
words holds the value of the variable text
=end
if word != redact
=begin
if word (which now holds the value of words that's
stored in the variable text, and which is the user's input)
is not equal to the value of the variable redact do something
=end
word = word + " "
=begin
increment the value of word by an empty space
why do I need to increment the value of word by an empty space?
=end
print "#{word}" #print the value of the variable word
else
print "REDACTED" #otherwise, print the value redacted
end
end
如果我使用由空格分隔的字符串并且仅当我更改时,程序才有效
word = word + ""
而不是
word = word + " "
如果有人为我逐步分解它,我将不胜感激。
我为它制作了一个视频,以便对其进行更直观的解释。 这是链接:ruby redaction video
谢谢。
【问题讨论】:
-
最初的“让我们从简单的开始”问题只需要一个循环来打印单词。您是在问这个问题还是更复杂的编辑匹配世界的问题?
-
另外,当你有
word = word + " "时,程序怎么不工作? -
我只是想了解它是如何工作的,而 word = word + " " 由于某种原因不起作用,我真的不知道为什么。
标签: ruby each control-flow redaction