为什么put()不打印在一行?

时间:2013-04-12 23:39:11

标签: ruby

这是一段代码:

def add(a, b) 
  a + b;
end

print "Tell number 1 : "
number1 = gets.to_f

print "and number 2 : "
number2 = gets.to_f

puts "#{number1}+#{number2} = " , add(number1, number2) , "\n"`

当我运行它时,我的结果分布在几行:

C:\Users\Filip>ruby ext1.rb
Tell number 1 : 2
and number 2 : 3
3.0+3.0 =
5.0


C:\Users\Filip>

为什么puts()不能在一行中打印,如何将输出保持在一行?

3 个答案:

答案 0 :(得分:3)

gets()包含换行符。将其替换为gets.strip更新:您更新了代码,因此如果您对使用浮点数感到满意,则不再相关。)

puts()为每个尚未在换行符中结尾的参数添加换行符。您的代码相当于:

print "#{number1}+#{number2} = ", "\n",
      add(number1, number2) , "\n",
      "\n"

您可以将puts替换为print

print "#{number1}+#{number2} = " , add(number1, number2) , "\n"`

或更好:

puts "#{number1}+#{number2} = #{add(number1, number2)}"

答案 1 :(得分:2)

Puts在输出结尾添加换行符。打印没有。试试打印。

http://ruby-doc.org/core-2.0/IO.html#method-i-puts

您可能还想将gets替换为gets.chomp

puts "After entering something, you can see the the 'New Line': "
a = gets
print a

puts "After entering something, you can't see the the 'New Line': "
a = gets.chomp
print a

答案 2 :(得分:1)

因为puts打印字符串后跟换行符。如果您不想换行,请改用print