Your First Program
Say hello to the world with puts
Every programmer remembers writing their very first program, and almost every programmer starts with the exact same one: a program that displays a friendly greeting on the screen. It is such a common tradition that this kind of program even has a nickname, "Hello, World." Today, you are joining that tradition in Ruby.
Meet puts
In Ruby, the easiest way to display text on the screen is a command called puts, short for "put string." Whatever you place after puts gets printed out, followed by a new line. Here is the classic example.
puts "Hello, world!"Try reading that line out loud: "put this string, Hello world, on the screen." That is exactly what it does.
Strings need quotes
Notice that the text "Hello, world!" is wrapped in double quotes. In Ruby, any piece of text is called a string, and strings almost always need to be wrapped in quotes so Ruby knows where the text begins and ends. If you forget the quotes, Ruby will get confused and show you an error instead of your message.
Printing more than one line
You can use puts as many times as you like, and each one will print its own line.
puts "Hello, world!"
puts "I am learning Ruby."
puts "This is fun!"That short program produces three separate lines of output, one after another, in the exact order they appear in your code. Ruby always runs your instructions from top to bottom, one at a time.
A close cousin: print
Ruby also has a command called print, which is almost the same as puts except it does not automatically add a new line after the text. For now, puts is the friendlier choice for beginners because it keeps your output neat and easy to read.
Do not worry about memorizing every detail right now. The best way to learn puts is simply to try it. Change the text inside the quotes and see what happens.
Quick check
Q1 Which keyword prints text to the screen in Ruby?
Q2 Why does text printed with puts need to be wrapped in quotes?
Want to save your progress? It's free.
Create a free account