Your First Ruby Program
Prerequisites: Installing Ruby
Create a file called hello.rb with this one line:
puts "Hello, world!"
Then run it from the folder that contains the file:
ruby hello.rb
Expected output
Hello, world!
That's a complete Ruby program. There is no main function and no
required boilerplate — Ruby runs the file from top to bottom.
puts("put string") prints a value followed by a new line."Hello, world!"is a string — a piece of text in quotes.- Parentheses around method arguments are optional:
puts("Hello, world!")does exactly the same thing. Ruby style usually leaves them off forputs.
A slightly longer program runs line by line:
puts "Hello, world!"
puts "I am learning Ruby."
puts 2 + 3
Hello, world!
I am learning Ruby.
5
Common mistakes
- Running
ruby hello.rbfrom the wrong folder givesNo such file or directory. Usecdto move into the folder first. - Mismatched quotes such as
puts "Hello'cause anunterminated stringsyntax error.
Practice
Write a program that prints your name on one line and your favorite food on the next.
Show solution
puts "Ada"
puts "Pizza"