Naming: ? returns a boolean, ! is the "dangerous" version
Classes & Modules
class User; attr_reader :name; def initialize(name); @name = name; end; end
Class with a constructor and reader
class Admin < User
Inheritance
module Greetable; def greet = "Hi, #{name}"; end
Module of reusable methods
include Comparable
Mix a module into a class
Point = Data.define(:x, :y)
Immutable value object (Ruby 3.2+)
Errors
begin ... rescue ZeroDivisionError => e ... ensure ... end
Handle an exception
raise ArgumentError, "age must be positive"
Raise an exception
class InsufficientFunds < StandardError; end
Custom exception class
user&.name
Safe navigation — nil instead of NoMethodError
Tooling
ruby app.rb
Run a script
irb
Interactive Ruby console
bundle init / bundle add rspec
Create a Gemfile / add a gem
bundle exec rspec
Run a command with the project's gem versions
bundle exec rubocop -a
Lint and auto-correct style
Cookies & your privacy
We use essential cookies to keep this site working and secure.
With your permission, we'd also like to use Google Analytics cookies to understand site traffic.
We don't use advertising or social media tracking cookies, and we honor Global Privacy Control (GPC) browser signals.
Learn more in our Privacy Policy.
Your browser is sending a GPC signal, so analytics stays off even if you accept.