Running Ruby

Ruby · Essentials · 8 min

Every Ruby journey starts with running code and inspecting values, and IRB is where Rubyists experiment.

Ruby code lives in .rb files and runs with ruby hello.rb. For experiments, start IRB, the interactive Ruby shell, with irb: type an expression and it prints the result. ruby -e 'puts 1 + 1' runs a one-liner, and ruby -v shows the version.

Three ways to print:

  • puts x prints x.to_s followed by a newline (arrays print one element per line).
  • print x prints without a newline.
  • p x prints x.inspect, the developer view: strings keep their quotes, and nil is shown as nil. It also returns its argument, so you can wrap it around an expression while debugging.

In Ruby everything is an object, including numbers, nil and true. You call methods on them with a dot: 5.even?, "ruby".upcase, nil.to_a. Even 1 + 2 is the method call 1.+(2).

Comments start with #. Parentheses around method arguments are optional (puts "hi" and puts("hi") are the same), and statements end at the line break, without semicolons.

By convention, methods ending in ? return a boolean (empty?), and methods ending in ! are the "dangerous" version of a method, usually one that modifies the receiver in place (upcase!).

Example

# hello.rb: run with `ruby hello.rb`
puts "Hello, Ruby!"        # Hello, Ruby!
puts RUBY_VERSION          # e.g. 3.4.7

p "quoted"                 # "quoted"
puts nil.inspect           # nil

puts 5.even?               # false
puts "ruby".upcase         # RUBY
puts 1.+(2)                # 3: operators are methods
puts 42.class              # Integer
puts nil.class             # NilClass

Remember

  • Run files with ruby file.rb and experiment in irb
  • puts shows to_s, p shows inspect (great for debugging)
  • Everything is an object; operators are method calls

Watch out for

  • Using puts to debug and missing that a value is nil or a string; use p instead.

Check yourself

  1. What does p "hi" print?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.ruby-lang.org/en/documentation/quickstart/

Builds on

Nothing: this is a foundation.

Unlocks