Ruby程序在终端中无法正常运行

时间:2015-12-22 17:08:58

标签: ruby windows command-line terminal git-bash

我正在编写非常基本的Ruby程序来学习类的变量和方法。我写了以下内容:

puts 'What is your favorite number?'
fav_num = gets.chomp.to_i
better_num = fav_num + 1
puts better_num.to_s + ' ' + 'is a much better number than ' + fav_num.to_s + '!'

当我使用ruby variables-methods.rb在我的终端中运行此程序时,它会转到下一行并且什么都不做。如果我输入一个数字,就会发生这种情况:

22
What is your favorite number?
23 is a much better number than 22!

我在终端更新了Ruby。

知道可能出现什么问题吗?

1 个答案:

答案 0 :(得分:2)

存在冲洗输入/输出流的问题。我不知道它是如何在你的终端中完成的,但是下面的代码应该可以解决问题(注意输出流的显式flush):

$stdout.puts 'What is your favorite number?'
$stdout.flush
fav_num = $stdin.gets.chomp.to_i
better_num = fav_num + 1
$stdout.puts better_num.to_s + ' is a much better number than ' + fav_num.to_s + '!'