Ruby Output Problem

M

Mikem94590

Hello all.
I am new to Ruby, and am created a simple program that takes a name,
and outputs "Hello " + name + ".". My problem is that this is putting
the output on multiple lines.

e.g: Hello Mike
 
B

Ben Lovell

[Note: parts of this message were removed to make it a legal post.]

Hello all.
I am new to Ruby, and am created a simple program that takes a name,
and outputs "Hello " + name + ".". My problem is that this is putting
the output on multiple lines.

e.g: Hello Mike
.

What am I doing wrong?

Below is the simple code I am using:

name = gets
puts "Hello " + name + "."
sleep
gets adds a newline so you should use chomp. Also, string interpolation is
usually preferable to concatenation. This example is better:

name = gets.chomp
puts "hello #{name}."
sleep

Ben
 
M

Mikem94590

[Note:  parts of this message were removed to make it a legal post.]



Hello all.
I am new to Ruby, and am created a simple program that takes a name,
and outputs "Hello " + name + ".".  My problem is that this is putting
the output on multiple lines.
e.g: Hello Mike
      .
What am I doing wrong?
Below is the simple code I am using:
name = gets
puts "Hello " + name + "."
sleep

gets adds a newline so you should use chomp. Also, string interpolation is
usually preferable to concatenation. This example is better:

name = gets.chomp
puts "hello #{name}."
sleep

Ben

Thank you for you quick reply. Your advice worked, and seems like
something that can be used for other purposes as well.
 
B

Ben Lovell

[Note: parts of this message were removed to make it a legal post.]

On Jun 25, 2009, at 11:24 , Ben Lovell wrote:

gets adds a newline so you should use chomp.

not quite. gets reads the newline that the user entered.
+1 point to you for passing my test ;)
 
R

Robert Klemme

Thank you for you quick reply. Your advice worked, and seems like
something that can be used for other purposes as well.

Another hint: if you want to see what's going on often using "p" instead
of "puts" helps because it will escape special chatercters. If applied
to variable "name" after "gets" you would have seen the newline at the end:

$ ruby19 -e 'n=gets;p n'
hello
"hello\n"

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,174
Messages
2,570,941
Members
47,476
Latest member
blackwatermelon

Latest Threads

Top