Your First Ruby Script
Writing, saving, and running a real .rb file, and the handful of building blocks every Ruby script leans on.
2 min read
irb is great for one-liners, but real programs live in .rb files. Let's write one and run it.
Writing and running a file
Create a file called greeting.rb:
puts "What's your name?"
name = gets.chomp
puts "Hello, #{name}! Welcome to Ruby."Run it from the terminal with the ruby command:
ruby greeting.rbputs prints a line of output followed by a newline. gets reads a line of input from the keyboard, and chomp strips the trailing newline character that gets includes — without chomp, name would have an invisible newline stuck to the end of it, which causes subtle bugs later when you compare or print it.
puts vs print vs p
Ruby has three common ways to print, and mixing them up is a common early stumbling block:
puts "hello" # hello\n -- adds a newline
print "hello" # hello -- no newline
p "hello" # "hello"\n -- inspects the value (shows quotes), adds a newlinep is especially useful while debugging, because it shows you the inspected value rather than the display value — p nil prints nil, while puts nil prints an empty line. When you're not sure why a value looks wrong, reach for p first.
Comments
# This is a single-line comment
=begin
This is a
multi-line comment block
=endIn practice, almost all Ruby code uses # comments; the =begin/=end block form exists but is rarely used idiomatically.
A slightly bigger example
puts "Enter two numbers, separated by a space:"
input = gets.chomp
a, b = input.split(" ").map(&:to_f)
sum = a + b
puts "#{a} + #{b} = #{sum}"A few things worth noticing even before later lessons cover them properly: split(" ") breaks the input string into an array on spaces, map(&:to_f) converts each piece to a float, and a, b = ... destructures the resulting two-element array into two variables in one line. Ruby is full of small conveniences like this — the underlying operations aren't unique to Ruby, but the syntax for expressing them tends to be shorter than in most other languages.
Running scripts with arguments
Ruby scripts can also read command-line arguments via the ARGV array:
# args.rb
puts "You passed: #{ARGV.join(", ")}"ruby args.rb foo bar
# You passed: foo, barThat's the full loop: write a .rb file, run it with ruby, and use puts/p to see what's happening. Everything from here builds on exactly this workflow.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.