Ruby: reference

An expressive language for scripts and the web: blocks, symbols and readable code, as in Rails.

Program structure

Minimal program

There is no separate main: code runs from top to bottom. puts prints a line and moves to a new one, print does not, and p shows a value the way it is written in code.

puts "Hello, world!"
print "No line break"
puts
p "quoted"

Running

Scripts with the .rb extension are run by the ruby interpreter. The -e flag runs a single line, and irb gives an interactive console for quick experiments.

ruby hello.rb

ruby -e 'puts 2 + 3'

irb    # interactive console

Variables and types

Variables and constants

Variables are created by assignment, and no type needs to be declared. A name starting with a capital letter, like MAX, is a constant and is not meant to be changed.

name = "Olena"
score = 0
score += 10
MAX = 100
puts "#{name} #{score} #{MAX}"

Basic types

Main types: Integer, Float, String, Symbol, true, false and nil. Integers can be arbitrarily large, and _ separates digit groups.

i = 42
big = 10_000_000_000
d = 3.14
ok = true
nothing = nil
puts [i.class, big.class, d.class, ok.class, nothing.class].inspect

Type conversion

The methods to_i, to_f, to_s convert the type. For a non-numeric string to_i gives 0, while the strict Integer("abc") raises an error.

puts "12".to_i + 1
puts 7.to_f / 2
puts 3.9.to_i
puts 42.to_s + "!"
puts "abc".to_i
puts Integer("12")

Strings

Interpolation

In double quotes #{expression} inserts a value. In single quotes interpolation does not work and the text stays as it is.

name = "Ruby"
a = 3
b = 4
puts "Hello, #{name}!"
puts "Sum: #{a + b}"
puts 'No interpolation: #{a}'

String methods

A method ending with ? returns a boolean, for example include?. Methods like upcase return a new string, while upcase! changes the existing one.

s = "Hello, World"
puts s.length
puts s.upcase
puts s[0, 5]
puts s.sub("World", "Ruby")
puts s.include?("World")
p s.split(", ")

Multiline strings

A <<~ heredoc lets you write text over several lines and strips the common indentation. The * operator repeats a string, and << appends to the end.

text = <<~TXT
  Line one
    Line two
TXT
puts text
puts "ab" * 3
s = "ab"
s << "c"
puts s

Conditions

if, elsif, else

The condition is not wrapped in parentheses, and the block ends with the word end. The branch is spelled elsif, not elseif. unless runs when the condition is false.

age = 16
if age < 12
  puts "child"
elsif age < 18
  puts "teen"
else
  puts "adult"
end
puts "ok" unless age < 0

case and when

case compares a value with the options in when, supports ranges and several values separated by commas. Like if, it returns a value.

day = 6
kind = case day
       when 1..5 then "weekday"
       when 6, 7 then "weekend"
       else "unknown"
       end
puts kind

Ternary operator and nil

The ternary operator looks like condition ? a : b. Only false and nil count as false, while 0 and an empty string are truthy. The &. form safely calls a method on nil.

n = 5
puts n.even? ? "even" : "odd"
puts "big" if n > 3
name = nil
puts name || "unknown"
puts name.nil?
p name&.upcase

Loops

times, upto, step

In Ruby loops are usually written with the iterators times, upto, step and each with a block. The range 1..3 includes the end, while 1...3 does not.

3.times { |i| puts i }
1.upto(3) { |i| print i, " " }
puts
0.step(10, 5) { |i| print i, " " }
puts
(1..3).each { |i| puts i * i }

while and until

while runs as long as the condition is true, and until as long as it is false. The until modifier can be placed after an expression on one line.

n = 3
while n > 0
  puts n
  n -= 1
end
k = 0
k += 1 until k == 4
puts k

loop, break and next

loop do is an infinite loop that break stops. The word next skips the rest of the iteration and moves on to the next one.

i = 0
loop do
  i += 1
  next if i.odd?
  break if i > 6
  puts i
end

Blocks and iterators

Block and yield

A block is a piece of code passed to a method. The method calls it with yield. A short block is written in { }, and a long one between do and end.

def twice
  yield 1
  yield 2
end

twice { |x| puts x * 10 }
twice do |x|
  puts x + 100
end

map, select, reduce

map transforms each element, select keeps the matching ones, reject drops them, and reduce folds a list into one value. The &:even? form is a shorthand for a block.

nums = [1, 2, 3, 4, 5]
p nums.map { |n| n * n }
p nums.select(&:even?)
p nums.reject(&:even?)
puts nums.reduce(0) { |sum, n| sum + n }
puts nums.sum

each_with_index

each_with_index gives an element together with its index. The %w[...] form creates an array of strings without quotes and commas, and zip pairs up two arrays.

fruits = %w[apple banana cherry]
fruits.each_with_index do |f, i|
  puts "#{i}: #{f}"
end
fruits.each_slice(2) { |pair| p pair }
p fruits.zip([1, 2, 3])

Methods

Defining a method

A method is defined with def, and the last evaluated expression becomes the result, so return is usually not needed. Parameters can have default values.

def add(a, b)
  a + b
end

def greet(name = "world")
  "Hello, #{name}!"
end

puts add(2, 3)
puts greet
puts greet("Ruby")

Keyword arguments

Parameters with a colon are passed by name in any order. Without a default value, like host:, the parameter is required.

def connect(host:, port: 80)
  "#{host}:#{port}"
end

puts connect(host: "localhost")
puts connect(port: 8080, host: "example.com")

Variable number of arguments

*nums collects extra arguments into an array, and **opts into a hash. A one-line method is written with =, and the multiple assignment a, b = ... unpacks an array.

def total(*nums)
  nums.sum
end

def info(**opts)
  opts
end

puts total(1, 2, 3)
p info(a: 1, b: 2)
def pair = [1, 2]
a, b = pair
puts a + b

Collections

Array

An array is an ordered list of any values. << and push append to the end, first and last take the edge elements, and sort returns a sorted copy.

a = [3, 1, 2]
a << 4
a.push(5)
p a
puts a.first, a.last, a.length
p a.sort
p a[1..2]
p a.include?(2)

Useful array methods

uniq removes duplicates, partition splits into two arrays, take takes the beginning, and compact removes nil. Most methods return a new array.

a = [4, 1, 3, 1]
p a.uniq
p a.sort.reverse
p a.min, a.max
p a.each_slice(2).to_a
p a.partition(&:even?)
p a.take(2)
p a.compact

Ranges

The range a..b includes both ends, while a...b excludes the right one. It can be turned into an array with to_a or traversed with the each method.

r = (1..5)
p r.to_a
p (1...5).to_a
p ('a'..'e').to_a
puts r.sum
puts r.include?(3)
p r.step(2).to_a

Symbols and hashes

Symbols

A symbol :name is an immutable name that exists in memory as a single instance. That makes symbols handy as hash keys. Conversions are done by to_sym and to_s.

s = :ruby
puts s
puts s.class
puts :a.equal?(:a)
puts "a".equal?("a")
puts "hello".to_sym.inspect
puts :hello.to_s

Hash

A hash stores key and value pairs. The name: form creates a symbol key. A missing key via [] gives nil, while fetch lets you specify a default value.

user = { name: "Olena", age: 16 }
puts user[:name]
user[:city] = "Dnipro"
p user
p user.fetch(:age)
p user[:none]
p user.fetch(:none, 0)
p user.key?(:age)

Iterating a hash

For a hash, each takes a |key, value| pair. to_h collects an array of pairs back into a hash, and Hash.new(0) sets a default value, handy for counting.

prices = { apple: 3, pear: 5 }
prices.each { |k, v| puts "#{k} = #{v}" }
p prices.map { |k, v| [k, v * 2] }.to_h
p prices.select { |_, v| v > 3 }
p prices.keys
p prices.values
puts prices.sum { |_, v| v }
counts = Hash.new(0)
"abca".each_char { |c| counts[c] += 1 }
p counts

Classes and modules

Class and attr_accessor

The constructor is the initialize method, and @name is an instance variable. attr_accessor creates a getter and a setter, attr_reader only a getter. to_s defines the text form.

class Person
  attr_accessor :name
  attr_reader :age

  def initialize(name, age)
    @name = name
    @age = age
  end

  def to_s = "#{@name} (#{@age})"
end

p1 = Person.new("Olena", 16)
p1.name = "Anna"
puts p1

Inheritance

The < sign names the parent class. A child class overrides methods, and super calls the parent version. A class inherits from only one parent.

class Animal
  def initialize(name) = @name = name
  def speak = "..."
end

class Dog < Animal
  def speak = "#{@name}: Woof!"
end

puts Dog.new("Rex").speak
puts Dog.superclass
puts Dog.new("Rex").is_a?(Animal)

Modules

A module is a set of methods. With include its methods are added to a class as a mixin, and methods with self. are called directly on the module, as a namespace.

module Greeting
  def hello = "Hello, #{name}!"
end

module Util
  def self.double(x) = x * 2
end

class User
  include Greeting
  attr_reader :name
  def initialize(name) = @name = name
end

puts User.new("Ann").hello
puts Util.double(4)

Errors

begin, rescue, ensure

Code in begin is protected: rescue catches an error of a given class. The ensure branch always runs, and else only when there was no error.

begin
  puts Integer("abc")
rescue ArgumentError => e
  puts "Error: #{e.message}"
else
  puts "No errors"
ensure
  puts "Always runs"
end

raise and custom errors

raise throws an error. A custom error class inherits from StandardError. A rescue clause can also be written directly in a method body.

class NegativeError < StandardError; end

def root(x)
  raise NegativeError, "negative: #{x}" if x < 0
  Math.sqrt(x)
end

begin
  root(-1)
rescue NegativeError => e
  puts e.message
end
puts root(9)

retry and rescue in a method

A rescue block can be written without begin inside def. The retry command runs the protected code again from the start, which suits repeated attempts.

def safe_div(a, b)
  a / b
rescue ZeroDivisionError
  puts "division by zero"
  nil
end

p safe_div(1, 0)
tries = 0
begin
  tries += 1
  raise "fail" if tries < 3
  puts "ok after #{tries}"
rescue
  retry
end

What is next

A lessons course for this language is on the way, and the reference is already available.

A course is on the way. For now only the reference is available; lessons and tasks will follow.