Hello World

September 3rd, 2007

As with any introduction to a programming language, I start off with a simple Hello World program. What takes me a minute to do in a language that I know, takes much longer with one that is foreign to me.

I’ll make this a bit more complicated, asking for the person’s name and telling them hello in my reply.

# Ask the user their name
puts "What is your name?"
user_name = gets

# Cunningly impress them with your response
puts "Hello, #{user_name.capitalize}!"

When I run the program and it asks for my name, I’ll type in Joe.

Output:

What is your name?
joe
Hello, Joe
!

The output of the program is not quite what I envisioned. The exclamation point appears on separate line. When I typed joe and pressed enter, the enter (or newline) is printed in the response. String object provides a method, chomp, that will move unwanted display characters, namely the enter key that I pressed. I’ll call chomp when I receive the input from the gets method.

# Ask the user their name
puts "What is your name?"
# Get the user name and remove newline characters
user_name = gets.chomp

# Cunningly impress them with your response
puts "Hello, #{user_name.capitalize}!"

Running the revised program, I hope that the response appears on one line when I tell the program that my name is Joe.

Output:

What is your name?
joe
Hello, Joe!

There you have it. My first Hello World program written in Ruby.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>