列出项,直到空 get 返回填充的数组 - 不连续填充数组



我正在尝试制作一些让我运行的东西列表很多单词,然后在我按Enter inter inter nrowe列出字符串的情况下返回一个排序的数组。现在,提示让我键入两行,然后仅添加了最后一个单词,然后返回并重新启动,而不是不断地向数组中添加单词。

def stuffsky
  other_one=[]
  puts "What would you like to add to the message? type a word please, then press Enter"
  while true 
    if gets.chomp != "n"
      other_one.push(gets)
    else 
      break
    end
    puts other_one
  end
end
stuffsky

也许您正在尝试做这样的事情?

def stuffsky
  other_one = []
  puts "What would you like to add to the message? type a word please, then press Enter"
  while true 
    word = gets.chomp
    break if word == ""
    other_one.push(word)
    puts "other_one: #{ other_one.join(' ') }"
  end
  other_one
end
puts "stuffsky: #{ stuffsky }"

运行时,输出:

fooeleth_one:foo酒吧其他_one:foo bar巴兹其他_one:foo bar bazsquepsky:[" foo"," bar"," baz"]

问题是您不记得gets返回的字符串:

if gets.chomp != ""
  other_one.push(gets)
else 
  break
end

加上您的逻辑很痛苦。反转逻辑,使您的单词为空时打破,否则继续。

每次参考gets时,您实际上都在调用一种方法,该方法在用户的输入行中读取并返回。因此,第一次说gets.chomp != "n" Ruby在输入行中读取以检查您的状况,然后第二次说other_one.push(gets) Ruby在第二行输入中读取以添加到other_one。因此,您可以通过每循环一次调用gets来解决此问题。

您的代码也有一些次要的代码质量/可读性问题。我可能会这样做:

# Extract line getter to seperate method
def gets_lines
  result = []
  loop do # Use loop instead of while true
    line = gets.chomp # Note: chomp gets rid of the newline at the end of the string
    break if line.empty? # A bit more readable than your other condition
    result << line
  end
  return result
end
def stuffsky
  puts "What would you like to add to the message? type a word please, then press Enter"
  puts gets_lines.sort # You forgot to sort the array in your code
end
stuffsky

样本运行:

您想添加什么消息?请输入一个单词,然后按Enter苹果橙子Aardvark狮子老虎Aardvark苹果狮子橙子老虎

最新更新