Ruby, lesson 1
A program that shows nothing is hard to trust. The first thing to learn in any language is how
to make it talk back. In Ruby the everyday tool for that is puts, short for "put string". It
writes a value to the screen and then moves to a new line.
Text inside quotes is a string. Ruby accepts double quotes ("hi") and single quotes
('hi'). Double quotes can do extra tricks you will meet in the next lesson, so many Ruby
programmers use them by default.
Notice there are no parentheses. In Ruby, puts "hi" and puts("hi") mean the same thing.
Leaving them off is the common style when a line calls just one method.
Ruby has three printing methods you will use all the time:
puts prints each value and ends it with a new line. Give it several values and each one
goes on its own line.print prints the values exactly as they are, with new line at the end.2 exercises to try what you just read.
p prints a developer-friendly view of a value. Strings keep their quotes, which helps
when you want to see exactly what a variable holds while debugging.Numbers print just like text. Ruby works out 7 * 6 first and then prints the result.
A # starts a comment. Ruby ignores everything from the # to the end of the line.
Comments are notes for the people who read your code, and that includes you next month.
For a longer note, you can wrap lines between =begin and =end. Both markers must start at
the very beginning of a line. In practice most Ruby code just uses several # lines.
Ruby starts at the first line of your file and runs each line in order until it reaches the end. There is no special starting function to write: the file itself is the program.
If Ruby hits a problem, it stops and prints an error message. The message names the file, the
line number and the kind of error, such as undefined local variable or method. Read it
carefully. It almost always points straight at the typo.
Write a program that prints exactly these two lines:
The program reads no input.
Mission control counts down on a single line, then announces the launch on the next line. Print exactly this:
Use print for the three count-down pieces so they stay on one line, and puts for the rest.
The program reads no input.
puts "Hello, World!"
puts "Ruby reads this file from the top down."puts "one", "two" # one
# two
print "Loading"
print "..."
puts "done" # Loading...done
p "spaces matter " # "spaces matter "
puts 7 * 6 # 42# Greet the user
puts "Welcome!" # a comment can sit after code tooHello, World!
I am learning Ruby.3..2..1..Liftoff!
We have liftoff.