红宝石推方法是交替的

Wil*_*uey 2 ruby push

cool_words = []

while true

    cool_words.push gets
    break if gets.chomp == ''

end

puts cool_words
Run Code Online (Sandbox Code Playgroud)

它只是推动第一个条目,然后是第三个,然后是第五个.我认为这是我打破循环的break方式,因为没有方法它就不会发生.

break当我在空行中按Enter 键时,我需要它离开循环.

提前致谢!

Ben*_*Lee 5

你在循环中调用了gets 两次.它第一次被推入阵列.第二次与空字符串进行比较以进行循环中断.但每次都要求换行.

你只想gets每个循环调用一次.因此,您可以将其保存在变量中,然后在代码中多次使用该变量.

cool_words = []

while true
    line = gets
    cool_words.push line
    break if line.chomp == ''
end

puts cool_words
Run Code Online (Sandbox Code Playgroud)

更新:@MicahelKohl在评论中指出,你可以更优雅地完成上述任务:

cool_words = []

until (line = gets).to_s.chomp.empty?
    cool_words << line
end

puts cool_words
Run Code Online (Sandbox Code Playgroud)

  • 为什么使用`while true`(Ruby有一个通用的`循环do`用于那个btw)和`break`当你有一个循环条件:`until(line = gets.chomp).empty?cool_words << line end` (2认同)