我正在编写非常基本的Ruby程序来学习类的variables和方法。 我写了以下内容:
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
在我的terminal中运行这个程序时,它会进入下一行,不执行任何操作。 如果我input一个数字,会发生这种情况:
22 What is your favorite number? 23 is a much better number than 22!
我在terminal上更新了Ruby。
任何想法可能会出错?
有流入/流出的问题。 我不知道如何在你的终端完成,但下面的代码应该做的伎俩(注意输出流的显式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 + '!'