Why doesn't puts() print in a single line?

后端 未结 3 1333
生来不讨喜
生来不讨喜 2021-01-22 03:10

This is a piece of code:

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

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

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

puts \"#{num         


        
3条回答
  •  面向向阳花
    2021-01-22 03:55

    gets() includes the newline. Replace it with gets.strip. (Update: You updated your code, so if you're happy working with floats, this is no longer relevant.)

    puts() adds a newline for each argument that doesn't already end in a newline. Your code is equivalent to:

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

    You can replace puts with print:

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

    or better:

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

提交回复
热议问题