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 键时,我需要它离开循环.
提前致谢!
你在循环中调用了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)
| 归档时间: |
|
| 查看次数: |
1862 次 |
| 最近记录: |