我想像这样运行这段代码
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
关于ruby - 如何打破 while = gets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13740667/