2

我想像这样运行这段代码

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>'

如何修复此代码?

4

3 回答 3

3

您还可以捕获信号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

参考Ruby Signal 的文档

于 2012-12-06T09:52:29.920 回答
1

试试Ctrl- D。这是你需要的吗?

于 2012-12-06T09:39:07.833 回答
0
count = Hash.new(0)

stop_condition = "\n"
until stop_condition == line = gets
  words = line.split
  words.each do |word|
    count[word] += 1
  end
end

当然,您可以break if line.chomp.empty?在 while 循环中使用 a,但我避免使用它,因为它确实是一个无限循环,您知道要从中逃脱的条件。这也不会退出程序,只是循环。

controlc并且controld对用户来说很奇怪,我会避免将这些东西用于非异常事件。

于 2012-12-06T10:09:05.230 回答