Hello, World in Ruby
Start with the smallest useful script and learn how Ruby runs code. Ruby executes files top‑to‑bottom; there’s no special main function.
First program
Create a file and run it with the Ruby interpreter. puts prints a string and appends a newline.
# hello.rb
puts "Hello, world!"
Run it:
ruby hello.rbexecutes the file and exits with status 0 on success- On Unix,
echo $?prints the previous command’s exit status
How Ruby runs code
- Ruby executes top‑level statements immediately
- Methods are only executed when called
- The current object at the top level is an instance of
Objectnamedmain
Make the script executable (Unix)
Add a shebang and mark as executable to run it directly.
#!/usr/bin/env ruby
puts "Hello, world!"
chmod +x hello.rb
./hello.rb
Interactive (IRB)
IRB is Ruby’s REPL for quick experiments. Exit with Ctrl‑D or exit.
# in your shell
irb
>> puts "Hello, world!"
>> 1 + 2
=> 3
Printing and debugging
Use print to avoid a newline, puts to append one, and p to show an object’s inspect representation (great for debugging).
print "no newline"
puts " with newline"
p [1, 2, 3] # => [1, 2, 3]
Tips:
STDOUT.putsandSTDERR.putswrite to the respective streamswarn("message")writes to STDERR with a newline
Comments and encoding
#starts a comment to end of line- Optional magic comment
# frozen_string_literal: truemakes string literals immutable (discussed later) - Ruby defaults to UTF‑8; you can declare encoding with
# encoding: UTF-8
Handy CLI flags
ruby -e 'puts 1+2'runs inline coderuby -W:2 script.rbenables more verbose warnings on newer Rubies
Summary
putsadds a newline;printdoesn’t;pshows inspect output for debugging- Run scripts with
ruby file.rbor useirbfor experiments; shebang +chmod +xruns files directly on Unix