列表项直到空得到返回填充的数组 - 不连续填充数组

时间:2014-01-20 18:29:50

标签: ruby arrays

我正在尝试创建允许我运行列表很多单词的内容,然后在按Enter键时返回已排序的数组,而不会列出字符串。现在,提示允许我键入两行,然后返回仅添加了最后一个单词的数组,然后循环返回并重新开始,而不是继续向数组添加单词。

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

2 个答案:

答案 0 :(得分:0)

也许你正试图做这样的事情?

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 }"

运行时输出:

foo
other_one: foo
bar
other_one: foo bar
baz
other_one: foo bar baz

stuffsky: ["foo", "bar", "baz"]

问题是你不记得gets在{/ p>}中返回的字符串

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

另外你的逻辑是痛苦的。反转逻辑,以便在单词为空时中断,否则继续。

答案 1 :(得分:0)

每次引用gets时,您实际上都在调用一个方法,该方法从用户读入一行输入并返回它。所以第一次当你说gets.chomp != "\n" Ruby读入一行输入以检查你的情况时,然后第二次你说other_one.push(gets) Ruby读入第二行输入以添加到{ {1}}。所以你可以通过每个循环只调用一次other_one来解决这个问题。

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

gets

示例运行:

What would you like to add to the message? type a word please, then press Enter
Apple
Orange
Aardvark
Lion    
Tiger

Aardvark
Apple
Lion
Orange
Tiger