GGistDev

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.rb executes 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 Object named main

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.puts and STDERR.puts write to the respective streams
  • warn("message") writes to STDERR with a newline

Comments and encoding

  • # starts a comment to end of line
  • Optional magic comment # frozen_string_literal: true makes 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 code
  • ruby -W:2 script.rb enables more verbose warnings on newer Rubies

Summary

  • puts adds a newline; print doesn’t; p shows inspect output for debugging
  • Run scripts with ruby file.rb or use irb for experiments; shebang + chmod +x runs files directly on Unix