Filip Bartuzi
Filip Bartuzi

Reputation: 5931

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

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 "#{number1}+#{number2} = " , add(number1, number2) , "\n"`

When I run it, my results are spread over several lines:

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


C:\Users\Filip>

Why doesn't puts() print in a single line, and how can keep the output on one line?

Upvotes: 3

Views: 7660

Answers (3)

Darshan Rivka Whittle
Darshan Rivka Whittle

Reputation: 34031

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)}"

Upvotes: 7

sunnyrjuneja
sunnyrjuneja

Reputation: 6123

Puts adds a newline to the end of the output. Print does not. Try print.

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

You might also want to replace gets with 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

Upvotes: 2

Chuck
Chuck

Reputation: 237010

Because puts prints a string followed by a newline. If you do not want newlines, use print instead.

Upvotes: 2

Related Questions