ruby - 如何打破 while = gets

标签 ruby while-loop interrupt

我想像这样运行这段代码

count = Hash.new(0)

while line = gets
  words = line.split
  words.each do |word|
    count[word] += 1
  end
end

count.sort{|a, b|
  a[1] <=> b[1]
}.each do |key, value|
  print "#{key}: #{value}\n"
end

但我不知道如何破解。点击 Command+C 返回

word_count.rb:3:in `gets': Interrupt
from word_count.rb:3:in `gets'
from word_count.rb:3:in `<main>'

如何修复此代码?

最佳答案

您还可以捕获发送到进程的信号Ctrl+C:

 count = Hash.new(0)
 trap("SIGINT") { 
   count.sort{|a, b|
     a[1] <=> b[1]
   }.each do |key, value|
     print "#{key}: #{value}\n"
   end
   exit!
 }
 while line = gets
   words = line.split
   words.each do |word|
     count[word] += 1
   end
 end

引用documentation of Ruby Signal

关于ruby - 如何打破 while = gets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13740667/

相关文章:

python - while 循环计数器比较两个列表

ruby - 没有 Rails 的 Mongoid

ruby-on-rails - 以任意顺序匹配多个 yield

php - 如何让 Ruby AES-256-CBC 和 PHP MCRYPT_RIJNDAEL_128 很好地协同工作

java - 如何让我的 While 循环使用用户输入进行计数而不是无限循环?

function - 带有子函数调用的奇怪 'while' 循环行为(MATLAB)

c - 检查全局变量线程安全保护的工具

linux-kernel - request_irq() 在内部做什么?

javascript - 在 Web Worker 仍在运行时向其发送消息

ruby-on-rails - Rails 4 ActiveRecord::StatementInvalid