【问题标题】:Ruby redaction program logic?Ruby 编辑程序逻辑?
【发布时间】: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


【解决方案1】:

您的视频中的问题是“nelson”与“nelson”不同,当您在打印之前在单词后面附加空格时,Codeacademy 评分看不到匹配项。

【讨论】:

    【解决方案2】:

    我在 2019 年 7 月阅读这个问题..

    因此,任何正在阅读此问题并对用户询问的以下部分感到困惑的人:

    单词=单词+“” =开始 将 word 的值增加一个空格 为什么我需要将 word 的值增加一个空格?

    所以答案是 + 号不是用于增加值,而是用于添加空格,而 + 号用作字符串连接符。所以它被放置在那里,以便搜索和显示任何单词,它们之间有一个空格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多