Introduction
Getting Started · Ruby 1
What Ruby Is
Ruby is an interpreted, dynamically typed, thoroughly object-oriented language: every value, even a number, is an object with methods. You write source code in a .rb file and the Ruby interpreter runs it; there is no compile step. Indentation is for people; end closes every block.
- Ruby 3 from ruby-lang.org, or a version manager such as rbenv. Check with
ruby --version. - An editor: VS Code with the Ruby LSP extension, RubyMine, or any text editor.
- irb — the interactive shell. Type
irb, then statements one at a time; each result is shown with=>. Great for trying things. - Script — save a file such as
hello.rband runruby hello.rb. This is how programs are delivered.
Your First Program
hello.rb
# My first Ruby program
puts "Hello, World!"Run it from a terminal
ruby hello.rbHello, World!Read it
- Lines starting with
#are comments; Ruby ignores them. putsis a method call that prints its argument and a newline. Parentheses are optional when the meaning is clear:puts("Hello")works too.- The text in quotes is a string. Double quotes allow
#{...}interpolation and escapes; single quotes are literal. - No semicolons, no
main: statements at the top of the file run in order.
puts, print and p
puts "Hello", "World" # each argument on its own line
print "No newline" # print adds nothing
print "\n"
p "quoted" # p shows the value the way irb does: "quoted"
puts 6 * 7 # numbers print too
puts "The answer is #{6 * 7}" # interpolation: any expression inside #{ }Hello
World
No newline
"quoted"
42
The answer is 42Blocks End with end, and Style
Where Java uses braces and Python uses indentation, Ruby uses the keyword end. Indent the inside by two spaces (the Ruby convention) so the matching end is easy to see.
if hours > 40
puts "Overtime" # inside the if
pay = pay * 1.5
end
puts "Done" # outside: runs every timeConventions
- Variables and methods in snake_case:
total_score,print_balance - Classes and modules in UpperCamelCase:
BankAccount - Constants in ALL_CAPS:
MAX_SIZE = 100(Ruby warns if you reassign one) - Methods that answer a question end in
?(empty?); methods that change the object in place end in!(sort!). - Two-space indentation, no tabs, lines under about 80 characters.
Comments
# A one-line comment
=begin
A block comment between =begin and =end,
each at the start of a line. Rare; most people use #.
=endThree Kinds of Errors
| Kind | When it shows up | Example |
|---|---|---|
| Syntax error | Before anything runs; Ruby points at the line | A missing end, unbalanced quotes, eles instead of else |
| Run-time error (exception) | While running; the program stops with a message and a line number | ZeroDivisionError, NoMethodError: undefined method for nil, NameError for a misspelled variable |
| Logic error | Never announced; the program runs and gives the wrong answer | Integer division where you meant a decimal, a loop that stops one early |
The most common Ruby error is undefined method ... for nil:NilClass. It means a variable or an array lookup produced nil (“nothing”) and you then called a method on it. Trace back to where the nil came from.
Programming with Numbers and Strings
Getting Started · Ruby 1
Variables and Types
A variable is a name for an object. You do not declare a type: Ruby looks at the value. Everything is an object, so numbers and strings have methods you call with a dot.
cans_per_pack = 6 # Integer
can_volume = 0.335 # Float
done = false # true or false (lowercase)
name = "Harry" # String
nothing = nil # nil: no value
MAX_SIZE = 100 # a constant
puts can_volume.class # Float
puts 6.even? # true: even an integer has methods
cans_per_pack += 1 # update; there is no ++ in Ruby| Type | Holds | Notes |
|---|---|---|
Integer | Whole numbers | Unlimited size: 2 ** 100 just works |
Float | Decimal numbers | About 15 significant digits; 0.1 + 0.2 == 0.3 is false |
true, false | The two booleans | Only false and nil count as false; 0 and "" are true |
String | Text | Mutable: methods ending in ! change it in place |
Symbol | A name, written :north | Lightweight constant labels, used as hash keys and options |
nil | “no value” | What a missing hash key or an empty method returns |
Arithmetic
| Operator | Meaning | Example |
|---|---|---|
+ - * | Add, subtract, multiply | 7 * 3 → 21 |
/ | Division. Integer ÷ integer drops the fraction | 7 / 2 → 3, but 7.0 / 2 → 3.5 |
% | Remainder (modulus) | 7 % 2 → 1; n % 2 == 0 tests for even, or just n.even? |
** | Power | 2 ** 10 → 1024 |
+= -= *= /= | Combine and assign | total += price |
Common math
minutes = 135
hours = minutes / 60 # 2
left = minutes % 60 # 15
r = Math.sqrt(2) # 1.4142135623730951
area = Math::PI * 3 ** 2
whole = 19.99.to_i # 19: to_i truncates
nearest = 19.99.round # 20
two_dp = 3.14159.round(2) # 3.14
big = [3, 9, 4].max # 9
dist = -4.5.abs # 4.5
dice = rand(1..6) # 1 to 6, inclusive
avg = sum.to_f / count # make one side a Float before dividingThe classic mistake: average = sum / count with two integers divides first, as integers. Convert one side first: sum.to_f / count or sum.fdiv(count).
Strings
greeting = "Hello"
n = greeting.length # 5 (also .size)
first = greeting[0] # "H" (positions start at 0; a one-character string)
last = greeting[-1] # "o" (negative counts from the end)
part = greeting[1, 2] # "el" (start, LENGTH)
part2 = greeting[1..2] # "el" (a range: 1 through 2)
where = greeting.index("l") # 2, or nil if not found
loud = greeting.upcase # "HELLO"
both = greeting + ", World" # concatenation needs strings on both sides
msg = "Total: #{3 + 4}" # interpolation: "Total: 7"
rep = "-" * 10 # "----------"
same = greeting == "Hello" # true: == compares the letters
inside = greeting.include?("ell") # true
greeting << "!" # append IN PLACE: greeting is now "Hello!"Useful string methods
| Method | Does |
|---|---|
s.downcase, s.upcase, s.capitalize | Change case |
s.strip, s.chomp | Remove surrounding whitespace; remove a trailing newline (what gets leaves on) |
s.sub("a", "b"), s.gsub("a", "b") | Replace the first / every a |
s.split(",") | An array of pieces |
words.join(", ") | Glue an array of strings together |
s.start_with?("Dr"), s.empty? | Tests that return true or false |
s.count("a"), s.reverse, s.chars | Count; reversed copy; array of characters |
Converting
count = "42".to_i # 42
price = "3.95".to_f # 3.95
text = 42.to_s # "42"
"abc".to_i # 0: to_i never raises; it stops at the first bad character
Integer("abc") # ArgumentError: use this when bad input should be an error
"Total: " + 7 # TypeError: use to_s or "#{...}"Methods without ! return a new string and leave the original alone: greeting.upcase does not change greeting. greeting.upcase! changes it in place (and returns nil if nothing changed, a famous gotcha).
Input and Formatted Output
volume.rb
print "Please enter the number of bottles: "
bottles = gets.chomp.to_i
print "Price per bottle: "
price = gets.chomp.to_f
total = bottles * price
puts format("Total: $%.2f for %d bottles", total, bottles)
puts "Total: $#{'%.2f' % total}" # the same, with the % operatorPlease enter the number of bottles: 3
Price per bottle: 1.5
Total: $4.50 for 3 bottles
Total: $4.50| Format | Meaning | Example |
|---|---|---|
%d | Integer | %5d right-aligns in 5 columns |
%f | Decimal | %.2f shows 2 decimals; %8.2f in 8 columns |
%s | String | %-10s left-aligns in 10 columns |
s.ljust(10), s.rjust(10), s.center(10) | Padding methods on strings | Often simpler than format for tables |
gets returns the whole line including the newline, so almost every call is gets.chomp. At the end of input gets returns nil; gets&.chomp survives that.
Decisions
Control Flow · Ruby 1
The if Statement
if floor > 13
actual_floor = floor - 1
elsif floor == 13
puts "There is no 13th floor."
else
actual_floor = floor
end| Ruby | Math | Note |
|---|---|---|
> >= | > ≥ | |
< <= | < ≤ | |
== | = | Two equals signs. One = assigns; Ruby warns about it inside a condition. |
!= | ≠ | |
(1..10).include?(x) or x.between?(1, 10) | 1 ≤ x ≤ 10 | Range tests instead of chained comparisons |
| Operator | True when |
|---|---|
a && b (or and) | both are true |
a || b (or or) | at least one is true |
!a (or not a) | a is false |
Use the symbol forms &&, ||, ! in conditions. The words and/or bind more loosely than = and are meant for flow control between statements.
Truthiness, Strings and Nothing
if word == "quit" # strings compare by content
if word.downcase == "quit" # ignore case
if word < other # alphabetical (uppercase sorts before lowercase)
if word.include?("a") # substring test
EPSILON = 1e-12
if (x - y).abs < EPSILON # floats: compare with a tolerance
if result.nil? # test for "no value"
if items.empty? # ask the object; do not compare to 0| Counts as false | Counts as true |
|---|---|
false and nil, nothing else | Everything else, including 0, 0.0, "" and [] |
Zero and the empty string are true in Ruby. Coming from Python or C this is the big surprise. Ask explicitly: if count.zero?, if name.empty?.
unless, Modifiers, case and the Ternary
unless and statement modifiers
unless logged_in # "if not"
puts "Please log in."
end
puts "Overtime" if hours > 40 # one-liner: the condition comes last
pay *= 1.5 unless exemptcase
case digit
when 1
name = "one"
when 2, 3
name = "two or three"
when 4..9
name = "several"
else
name = "many"
end
# case works with values, ranges, classes and patterns; no break neededcase as an expression
grade = case score
when 90.. then "A"
when 80...90 then "B"
when 70...80 then "C"
else "F"
end
# .. includes the end; ... excludes itThe ternary operator
label = n.even? ? "even" : "odd"
larger = a > b ? a : b
# condition ? value_if_true : value_if_falseif, unless and case are all expressions: they return the value of the branch that ran, so x = if ... end is normal Ruby.
Mistakes to Watch For
- Forgetting
end. Count them, or let your editor fold the blocks. - Writing
else ifinstead ofelsif: it opens a nested if that needs its ownend. - Comparing a number to the string the user typed:
gets.chomp >= 18is an error. Convert withto_ifirst. if done == trueworks but is noise; writeif done. Likewiseunless done.- An
elsifchain stops at the first true test, so order the ranges from largest down or smallest up.
Loops
Control Flow · Ruby 1
while, until and the Iterators
Ruby has while and until, but most counting is done with iterator methods that take a block: times, each, upto and step. A block is the code between do ... end (or { ... } for one line); the names between the pipes receive each value.
# while: years until the balance doubles
year = 0
while balance < 2 * initial
year += 1
balance = balance + balance * RATE / 100
end
until balance >= 2 * initial # "while not"
balance += balance * RATE / 100
end
# counting with blocks
5.times { |i| puts i } # 0 1 2 3 4
1.upto(10) { |i| puts i * i } # 1 to 10
10.downto(1) { |i| puts i }
(1..10).each do |i| # a range, multi-line block
puts "#{i} squared is #{i * i}"
end
0.step(100, 10) { |x| puts x } # 0, 10, 20, ... 100
# every element, no index needed
"Hello".each_char { |ch| puts ch }
[32, 54, 67].each { |v| total += v }| Range | Produces |
|---|---|
(1..5) | 1, 2, 3, 4, 5 (two dots include the end) |
(1...5) | 1, 2, 3, 4 (three dots exclude it) |
(0...items.length) | every valid index |
("a".."e") | a, b, c, d, e |
(1..5).to_a | the range as an array [1, 2, 3, 4, 5] |
Ruby’s for x in 1..5 exists, but idiomatic Ruby uses each. Unlike each, for leaks its variable into the surrounding scope.
Common Loop Algorithms
Sum, average, count
total = 0
count = 0
loop do
print "Value (blank to finish): "
line = gets.chomp
break if line.empty?
total += line.to_f
count += 1
end
puts "Average: #{total / count}" if count > 0Value (blank to finish): 10
Value (blank to finish): 20
Value (blank to finish): 30
Value (blank to finish):
Average: 20.0Every accumulating loop has the same three parts: set up before (total = 0, count = 0), update inside (total += line.to_f), use after the loop ends. total is a Float because to_f made it one, so the division is not integer division. The if count > 0 guard matters: with no values, 0.0 / 0 prints NaN rather than raising.
Maximum and minimum
largest = values[0] # start with the first value
values.each do |v|
largest = v if v > largest
end
# or simply: largest = values.maxSentinel value
print "Salary, -1 to finish: "
salary = gets.chomp.to_f
while salary != -1
total += salary
print "Salary, -1 to finish: "
salary = gets.chomp.to_f
endPrompting until valid, with loop and break
value = nil
loop do
print "Enter a positive number: "
value = gets.chomp.to_i
break if value > 0
end
puts "You entered #{value}"
# There is also begin ... end while cond, which runs the body firstCounting matches
spaces = 0
text.each_char { |ch| spaces += 1 if ch == " " }
# or: spaces = text.count(" ")Finding the first match
position = nil
values.each_with_index do |v, i|
if v == target
position = i
break
end
end
# or: position = values.index(target)Nested Loops and Loop Tools
Nested loops: a table
(1..3).each do |row|
(1..4).each do |col|
print format("%4d", row * col)
end
puts # end the row
end 1 2 3 4
2 4 6 8
3 6 9 12each_with_index and zip
names.each_with_index do |name, i| # value and index together
puts "#{i + 1}. #{name}"
end
names.each.with_index(1) { |name, n| puts "#{n}. #{name}" } # count from 1
names.zip(scores).each do |name, score| # two arrays in step
puts "#{name}: #{score}"
endbreakleaves the innermost loop or block;nextskips to the next turn (what other languages callcontinue).loop do ... endis an infinite loop you leave withbreak. Ruby has no plaindo-while;begin ... end while condis the closest.- Prefer
eachover an index loop whenever you only need the values. Reach foreach_with_indexwhen you need the position too. - Never change an array while iterating over it; build a new one instead.
Off-by-One and Other Traps
(1...n)stops atn - 1. For 1 through n write(1..n). Two dots in, three dots out.- A
whilewhose condition never changes is infinite. Ctrl+C stops it; then make sure the body moves toward the exit. - Float counters drift:
x = 0; x += 0.1 while x != 1never stops. Count with integers and compute the float inside. - A block parameter (
|i|) is local to the block. A variable first assigned inside a block also vanishes when the block ends; create it before the loop if you need it after. - Tracing by hand with a tiny input (n = 2) catches most loop bugs in a minute.
Functions (Methods)
Control Flow · Ruby 1
Defining and Calling
In Ruby a function is called a method. def defines it; it runs only when called. The value of the last expression is returned automatically, so return is only needed to leave early. Define methods above the code that calls them.
# Computes the volume of a cube with the given side length.
def cube_volume(side_length)
side_length ** 3 # the last expression is the return value
end
result = cube_volume(2) # the call; 2 is the argument
puts result # 8
puts cube_volume(1.5) # 3.375
puts cube_volume 1.5 # parentheses optional; use them when it reads better| Part | In the example | Rules |
|---|---|---|
| Header | def cube_volume(side_length) | def, the name, parameters in parentheses |
| Body | the indented lines | Runs each time the method is called |
| Return value | side_length ** 3 | The last expression evaluated; return x leaves early with x; a method that ends with puts returns nil |
end | end | Closes the method |
Parameters, Return Values and nil
Several results
def read_rect
print "Width: "
width = gets.chomp.to_f
print "Height: "
height = gets.chomp.to_f
[width, height] # return an array...
end
w, h = read_rect # ...and unpack it
def area_and_perimeter(w, h)
return w * h, 2 * (w + h) # return with commas makes an array too
endDefault and keyword arguments
def greet(name, greeting = "Hello", punctuation: "!")
"#{greeting}, #{name}#{punctuation}"
end
greet("Ann") # Hello, Ann!
greet("Ann", "Hi") # Hi, Ann!
greet("Ann", punctuation: "?") # Hello, Ann?Methods without a useful return value
def box_string(contents)
n = contents.length
puts "-" * (n + 2)
puts "!#{contents}!"
puts "-" * (n + 2)
end
box_string("Hello") # prints; returns nil (puts returns nil)
x = box_string("Hi") # legal but pointless: x is nilArguments are references to objects
def add_interest(balance, rate)
balance = balance + balance * rate / 100 # rebinds the local name only
end
def append_bonus(scores)
scores << 10 # changes the caller's array
end
savings = 1000
add_interest(savings, 5)
puts savings # still 1000
my_scores = [90, 85]
append_bonus(my_scores)
p my_scores # [90, 85, 10]A method cannot make the caller’s variable point at a new object, so for numbers you return the result. It can change the inside of a mutable object such as an array or string passed in (<<, push, upcase!). Methods ending in ! are the ones that do.
Mistakes to watch for
- Wrong number of arguments:
area_and_perimeter(3)stops withwrong number of arguments (given 1, expected 2) (ArgumentError). Every parameter without a default must be supplied. - Calling a method above its
def. The file runs top to bottom, soputs cube_volume(2)placed beforedef cube_volumegivesundefined method `cube_volume' for main (NoMethodError). Put the definitions first. - Using the value of a method whose last line is
puts:x = box_string("Hi")setsxtonil, and the firstx + 1later fails withundefined method `+' for nil (NoMethodError). Return the value and let the caller print. - An
ifwith noelseas the last expression returnsnilwhen the test is false. Add theelsebranch or an explicitreturn.
Blocks, Scope and Stepwise Refinement
Methods that take a block
def repeat(n)
n.times { yield } # yield runs the block the caller passed
end
repeat(3) { puts "Hip" }
def measure
start = Time.now
yield
Time.now - start # seconds the block took
end
seconds = measure { 1_000_000.times { 2 + 2 } }Scope
- A local variable created inside a method exists only during that call.
- A method cannot see local variables from outside it, even ones defined above it in the file. Pass what it needs as arguments.
- A block can see the variables around it, which is why
total += vinsideeachworks. $globalvariables exist but are a code smell; constants (RATE = 5) are the normal way to share a fixed value.
Stepwise refinement: write the top level as a list of calls to methods that do not exist yet, each named for one job (read_scores, compute_average, print_report), then write each method. Keep methods short enough to read without scrolling, and describe each one in a comment above it.
Lists: Arrays
Data · Ruby 1
Creating and Indexing
An array holds a sequence of values in order. Arrays grow and shrink, may mix types, and are mutable. Positions start at 0; negative positions count from the end. Reading past the end gives nil, not an error.
values = [32, 54, 67.5, 29, 35]
empty = []
zeros = Array.new(10, 0) # ten zeros
words = %w[apple banana cherry] # ["apple", "banana", "cherry"] without the quotes
first = values[0] # 32
last = values[-1] # 35 (also values.last)
values[1] = 60 # replace
n = values.length # 5 (also .size)
values[5] # nil: past the end, no error
values[10] = 1 # grows the array; positions 5 to 9 become nil
middle = values[1, 2] # [60, 67.5]: start, length
middle = values[1..2] # the same, with a rangeVisiting every element
values.each { |v| puts v } # the values
values.each_with_index do |v, i| # value and position
puts "#{i}: #{v}"
end
(0...values.length).each { |i| puts values[i] } # only when you must countCommon array algorithms, the Ruby way
total = values.sum
largest = values.max
smallest = values.min
average = values.sum.to_f / values.length
position = values.index(target) # nil if absent
found = values.include?(target)
values[i], values[j] = values[j], values[i] # swapArray Methods and Aliasing
| Operation | Does | Returns |
|---|---|---|
a.push(x) or a << x | Adds x to the end | the array (so a << 1 << 2 chains) |
a.insert(i, x) | Puts x at position i, later ones shift right | the array |
a.pop / a.shift | Removes and returns the last / the first element | the element |
a.delete(x) / a.delete_at(i) | Removes every x / the element at i | the removed value, or nil |
a.index(x) | Position of the first x | an Integer or nil |
a.include?(x) | Membership test | true or false |
a.sort / a.sort! | Sorted copy / sorts in place | a new array / the same array |
a.reverse, a.uniq, a.compact | Reversed copy; without duplicates; without nils | new arrays (add ! for in place) |
a.first(n), a.last(n), a.take(n), a.drop(n) | Slices from the ends | new arrays |
a.join(", "), a.flatten, a.count(x) | Glue into a string; un-nest; count |
Aliasing
a = [1, 2, 3]
b = a # b is another NAME for the same array
b << 4
p a # [1, 2, 3, 4]
c = a.dup # a real (shallow) copy
c << 5
p a # [1, 2, 3, 4]: unchangedSlices and ranges
nums = [10, 20, 30, 40, 50]
nums[1..2] # [20, 30]
nums[0, 2] # [10, 20]
nums[3..] # [40, 50] (endless range)
nums[..1] # [10, 20] (beginless range)
nums.each_slice(2).to_a # [[10, 20], [30, 40], [50]]
nums[1..2] = [7] # replace a slice: [10, 7, 40, 50]Assignment does not copy an array. After b = a both names see every change. Use dup when you need two independent arrays.
Transforming Arrays with Blocks, and Tables
map, select, reject, reduce
squares = (1..5).map { |x| x * x } # [1, 4, 9, 16, 25]
evens = values.select { |x| x.even? } # keep the ones that pass
odds = values.reject(&:even?) # the &:method shortcut
upper = names.map(&:upcase)
total = values.reduce(0) { |sum, x| sum + x } # fold; or values.sum
big_first = values.sort_by { |x| -x }
any_big = values.any? { |x| x > 50 }
all_pos = values.all?(&:positive?)
by_size = words.group_by(&:length) # a hash: length => [words]Destructuring and nested arrays
point = [3, 4]
x, y = point # unpacking
first, *rest = [1, 2, 3] # first = 1, rest = [2, 3]
pairs = [["Ann", 90], ["Bob", 85]]
pairs.each do |name, score| # a block can unpack each pair
puts "#{name}: #{score}"
endTwo-dimensional arrays
# A table: an array of rows, each row an array
table = Array.new(3) { Array.new(4, 0) } # 3 rows of 4 zeros (NOT Array.new(3, Array.new(4, 0)): that shares one row)
table[1][2] = 7
table.each do |row|
puts row.map { |v| format("%4d", v) }.join
end
rows = table.length
cols = table[0].length
column_total = table.sum { |row| row[1] } 0 0 0 0
0 0 7 0
0 0 0 0Mistakes to watch for
- Reading past the end gives
nil, and the crash comes one step later:values[5].upcasestops withundefined method `upcase' for nil (NoMethodError). Checki < values.lengthor usevalues.fetch(i), which raises anIndexErrorat the lookup itself. eachreturns the original array, not the block results:squares = values.each { |x| x * x }leavessquaresequal tovalues. Usemapwhen you want the results.values.sort,values.map,values.uniqreturn new arrays and leavevaluesalone. Either assign the result (values = values.sort) or use the!form (values.sort!).Array.new(3, [])makes three names for one inner array, sotable[0] << 1appears in every row. Use the block formArray.new(3) { [] }to get three separate arrays.
Files and Exceptions
Data · Ruby 1
Reading and Writing Text Files
line_numberer.rb
# Copy input.txt to output.txt with line numbers
File.open("output.txt", "w") do |out|
line_number = 1
File.foreach("input.txt") do |line| # one line at a time, newline included
out.print "/* #{line_number} */ #{line}"
line_number += 1
end
end
# the block form closes the file for you, even when something goes wronginput.txt output.txt
Mary had a lamb /* 1 */ Mary had a lamb
Its fleece was /* 2 */ Its fleece was
white as snow /* 3 */ white as snow| Call | Does |
|---|---|
File.open(name, "r") { |f| ... } | Opens for reading; Errno::ENOENT if it does not exist; closes at the end of the block |
File.open(name, "w") | Opens for writing; creates the file or erases an existing one |
File.open(name, "a") | Opens for appending at the end |
File.foreach(name) { |line| ... } | The usual way to read: every line, including its \n |
File.read(name) | The whole file as one string |
File.readlines(name, chomp: true) | An array of lines, newlines removed |
f.gets | The next line, or nil at the end |
f.puts, f.print, f.write | Write to the file, like printing to the screen |
File.exist?(name) | Test before opening |
How to read a file safely, step by step
- 1. Decide what you need from it. One line at a time (
File.foreach, uses almost no memory), every line as an array (File.readlines(name, chomp: true)), or the whole text (File.read). - 2. Open it in a block or use one of the class methods above; never
f = File.open(...)without a matchingf.close. The block form closes the file even if an exception is raised inside it. - 3. Strip the newline from each line with
chompbefore comparing or converting it:"92\n".to_ihappens to work, but"quit\n" == "quit"isfalse. - 4. Convert and check each piece:
to_iandto_fturn bad text into 0 silently, so useInteger(text)orFloat(text)when a bad value should stop the program. - 5. Rescue what can really happen at the top level:
Errno::ENOENTfor a missing file,ArgumentErrorfromInteger(...)for bad data. The next section shows thebegin/rescueblock.
Mistakes to watch for
- A wrong name or wrong folder:
No such file or directory @ rb_sysopen - input.txt (Errno::ENOENT). Ruby looked in the working directory; printDir.pwdto see which folder that is, or give a full path. - Forgetting
chompand then printing withputs: every line comes out double-spaced, because the line already ends in\nandputsadds another. - Opening the file you meant to read with
"w": it is emptied the instant it is opened, before you notice. Read with"r"(the default) and write to a different name.
Taking a line apart
line = "Smith, Jane, 92\n"
parts = line.chomp.split(", ") # ["Smith", "Jane", "92"]
score = parts[2].to_i
File.foreach("data.txt") do |line|
line.split.each { |word| count += 1 } # whitespace-separated words
endReading numbers
# One number per line
values = File.readlines("numbers.txt", chomp: true)
.reject(&:empty?)
.map(&:to_f)
# Several per line
File.foreach("numbers.txt") do |line|
line.split.each { |token| total += token.to_f }
endFile names are relative to the working directory, usually the folder you ran Ruby from. Command-line arguments are in the ARGV array: ruby prog.rb input.txt gives ARGV[0] == "input.txt".
Exceptions
When something goes wrong at run time Ruby raises an exception. If nothing handles it, the program prints the error and stops. You can raise your own and rescue the ones you can recover from.
Raising
def withdraw(balance, amount)
raise ArgumentError, "Amount exceeds balance" if amount > balance
balance - amount
endRescuing
begin
value = Integer(File.read(filename).lines.first)
puts "Read #{value}"
rescue Errno::ENOENT
puts "File not found: #{filename}"
rescue ArgumentError => e
puts "Not a number: #{e.message}"
endFile not found: data.txt (when data.txt does not exist)
Not a number: invalid value for Integer(): "abc\n" (when its first line is abc)
Read 42 (when its first line is 42)Ruby tries the rescue clauses in order and runs the first one whose class matches; the code after the failing line inside begin is skipped, so puts "Read ..." never runs on an error. => e gives the exception object a name so you can print e.message or e.class.
| Exception | Raised when |
|---|---|
ArgumentError | Right type, wrong value: Integer("abc"), wrong number of arguments |
TypeError | Wrong type: "3" + 4 |
NoMethodError | Calling a method the object does not have, very often on nil |
NameError | A misspelled variable or constant |
ZeroDivisionError | Integer division by zero (float division gives Infinity instead) |
KeyError | hash.fetch(key) for a key that is not there |
Errno::ENOENT | Opening a file that does not exist |
StandardError | The parent of all of these: what a bare rescue catches |
The Full begin Block and Your Own Exceptions
else, ensure and retry
attempts = 0
begin
attempts += 1
f = File.open(filename)
rescue Errno::ENOENT
puts "Cannot open #{filename}"
retry if attempts < 3 # run the begin block again
else
data = f.read # only when no exception happened
f.close
ensure
puts "Done" # runs no matter what
endA custom exception class
class InsufficientFundsError < StandardError
end
def withdraw(balance, amount)
raise InsufficientFundsError, "Balance is #{balance}" if amount > balance
balance - amount
end
begin
balance = withdraw(balance, 500)
rescue InsufficientFundsError => e
puts "Sorry: #{e.message}"
end- Raise early: check arguments at the top of a method and raise with a clear message.
- Rescue late: handle where you can actually do something, usually at the top level or in the input loop, not where the problem was found.
- Rescue the specific class. A bare
rescuecatches everyStandardError, which hides typos;rescue Exceptionis worse and even swallows Ctrl+C. - Inside a method,
rescuecan follow the body directly withoutbegin:def read ... rescue Errno::ENOENT ... end. - Prefer the block form
File.open(...) do |f| ... endtoensure f.close; it closes for you.
Sets and Dictionaries: Set and Hash
Data · Ruby 1
Sets
A Set holds values with no duplicates and no promised order. Adding a value that is already there does nothing. Use a set when the question is only “is it in there?” or to collect distinct things. It lives in the standard library: require "set" (automatic in Ruby 3.2 and later).
require "set"
names = Set.new(["Romeo", "Juliet"])
names << "Mercutio" # add (also names.add)
names << "Romeo" # ignored: already present
puts names.size # 3
puts names.include?("Juliet") # true: very fast
names.delete("Romeo")
names.sort.each { |n| puts n } # sets have no order; sort for display
distinct = words.to_set # the distinct words in an array
distinct = words.uniq # or just an array without duplicates| Operation | Operator | Method |
|---|---|---|
| Union: in either | a | b | a.union(b) |
| Intersection: in both | a & b | a.intersection(b) |
| Difference: in a but not b | a - b | a.difference(b) |
| Subset test | a <= b | a.subset?(b) |
Arrays support |, & and - too, so for small collections words.uniq and a & b on plain arrays are common. A Set is worth it when membership tests are frequent or the collection is large.
Hashes (Dictionaries)
A Hash stores key → value pairs. Each key appears once and looks up its value directly. Keys are most often symbols (:name) or strings; values can be anything, including arrays and other hashes. Hashes keep insertion order.
contacts = { "Fred" => 7235591, "Mary" => 3841212 } # string keys use =>
options = { color: "red", size: 10 } # symbol keys: the short form
contacts["Sarah"] = 2213278 # add or replace
number = contacts["Fred"] # look up; nil if absent (no error!)
number = contacts.fetch("Bob", 0) # 0 instead of nil; fetch("Bob") raises KeyError
if contacts.key?("Mary") # key test (also has_key?, include?)
contacts.delete("Mary")
end
puts contacts.length
contacts.each do |name, number| # key and value together, in insertion order
puts "#{name}: #{number}"
end
contacts.each_key { |name| puts name }
contacts.values.sum
puts options[:color] # "red"Counting with a hash
# How many times does each word occur?
counts = Hash.new(0) # 0 is the default for missing keys
text.downcase.split.each do |word|
counts[word] += 1
end
# the most common word
best = counts.max_by { |word, c| c } # ["the", 12]
# or let the library do it:
counts = text.downcase.split.tally
counts.sort_by { |w, c| -c }.first(3)# with text = "the cat and the hat and the bat"
p counts # {"the"=>3, "cat"=>1, "and"=>2, "hat"=>1, "bat"=>1}
p best # ["the", 3]
p counts.sort_by { |w, c| -c }.first(3) # [["the", 3], ["and", 2], ["cat", 1]]Hash.new(0) is what makes counts[word] += 1 work on the first sighting of a word: without the default, counts[word] is nil and nil + 1 fails with undefined method `+' for nil (NoMethodError). max_by hands each pair to the block and keeps the pair with the largest block value.
Grouping with a hash of arrays
by_letter = Hash.new { |hash, key| hash[key] = [] } # a fresh array per new key
names.each do |name|
by_letter[name[0]] << name
end
# or in one call
by_letter = names.group_by { |name| name[0] }Building and transforming hashes
squares = (1..5).to_h { |x| [x, x * x] } # {1=>1, 2=>4, 3=>9, 4=>16, 5=>25}
inverted = contacts.invert # swap keys and values
adults = people.select { |name, age| age >= 18 } # a smaller hash
names = people.map { |name, age| name } # an arrayh[key] on a missing key returns nil, silently. The NoMethodError on nil shows up later, somewhere else. Use fetch when a missing key is a bug, or give the hash a default with Hash.new(0).
Choosing a Collection
| You need | Use |
|---|---|
| Values in order, by position, possibly repeated | an Array |
| Membership only, no duplicates | a Set (or array.uniq for small cases) |
| Look up a value by a key | a Hash |
| First in, first out | an Array with push and shift |
| Last in, first out | an Array with push and pop |
| A fixed group of named values | a Struct: Point = Struct.new(:x, :y) |
Symbols vs strings as keys: options[:color] and options["color"] are different keys. Pick symbols for fixed, program-defined names and strings for data that comes from outside (files, user input).
Objects and Classes
Objects and Algorithms · Ruby 1
Classes Describe, Objects Are
A class is a blueprint: it says what data each object carries (instance variables, written @name) and what each object can do (methods). An object is one instance, made with ClassName.new. Strings, arrays and hashes are objects of built-in classes; now you write your own.
bank_account.rb
# A bank account has a balance that can be changed by deposits and withdrawals.
class BankAccount
# Constructs a bank account with the given balance (zero by default).
def initialize(initial_balance = 0.0)
@balance = initial_balance
end
# Deposits money into the account.
def deposit(amount)
@balance += amount
end
def withdraw(amount)
raise ArgumentError, "Amount exceeds balance" if amount > @balance
@balance -= amount
end
# Gets the current balance.
def balance
@balance
end
def to_s
format("BankAccount(balance=%.2f)", @balance)
end
endUsing the class
harrys_checking = BankAccount.new # calls initialize with the default
moms_savings = BankAccount.new(5000)
harrys_checking.deposit(2000)
moms_savings.withdraw(500)
puts harrys_checking.balance # 2000.0
puts moms_savings # BankAccount(balance=4500.00): puts calls to_sThe Pieces of a Class
| Piece | Looks like | Notes |
|---|---|---|
initialize | def initialize(initial_balance = 0.0) | The constructor: new creates the object and calls it; set every instance variable here |
| Instance variable | @balance | One per object, always private: nothing outside the class can read @balance directly. An unset one reads as nil |
| Mutator method | deposit, withdraw | Changes the object |
| Accessor method | balance | Reports without changing. Ruby names it after the thing, not get_balance |
self | inside a method | The object the method was called on; usually implicit |
to_s | def to_s | What puts and "#{...}" show; inspect is what p and irb show |
attr_accessor writes the boring methods for you
class BankAccount
attr_reader :balance # defines def balance; @balance; end
attr_accessor :owner # defines owner and owner=(value)
def initialize(owner, initial_balance = 0.0)
@owner = owner
@balance = initial_balance
end
end
acct = BankAccount.new("Harry")
acct.owner = "Harry Morgan" # calls owner=
puts acct.balance
acct.balance = 5 # NoMethodError: attr_reader made no writerObject references
a = BankAccount.new(1000)
b = a # b refers to the SAME object
b.deposit(500)
puts a.balance # 1500.0
c = nil # refers to nothing
c.deposit(1) # NoMethodError: undefined method 'deposit' for nilForgetting the @ is the classic mistake: writing balance = 0 inside a method creates a throwaway local variable, and the instance variable stays nil, which surfaces later as NoMethodError for nil.
Class Methods, Comparisons and Design
Class-level data and methods
class BankAccount
@@last_number = 1000 # class variable: shared by all accounts
INTEREST_RATE = 2.5 # constant
def initialize
@@last_number += 1
@number = @@last_number
@balance = 0.0
end
def self.round_cents(x) # class method: BankAccount.round_cents(3.456)
(x * 100).round / 100.0
end
endMaking objects behave like built-ins
class Point
include Comparable # gives <, <=, ==, >, between?, clamp from <=>
attr_reader :x, :y
def initialize(x, y)
@x, @y = x, y
end
def <=>(other) # -1, 0 or 1
[x, y] <=> [other.x, other.y]
end
def +(other)
Point.new(x + other.x, y + other.y)
end
def to_s
"(#{x}, #{y})"
end
endWhat Comparable and <=> buy you
a = Point.new(1, 2)
b = Point.new(1, 5)
puts a < b # true: Comparable calls your <=> and checks for -1
puts a == Point.new(1, 2) # true: == also comes from <=> returning 0
puts a + b # (2, 7): your + method, then to_s
puts [b, a, Point.new(0, 9)].sort.join(" ") # sort uses <=> too
puts [a, b].max # (1, 5)true
true
(2, 7)
(0, 9) (1, 2) (1, 5)
(1, 5)- Start with the public interface: what should callers be able to do? Write the method names and comments first.
- Then pick the instance variables that make those methods possible, and set every one in
initialize. - Put helper methods under a
privateline near the bottom of the class so they cannot be called from outside. - A class should be about one thing. If you cannot say what an object of the class is in a sentence, split it.
- Test the class alone in irb (
require_relative "bank_account") before using it elsewhere.
Inheritance and Modules
Objects and Algorithms · Ruby 1
Extending a Class
Inheritance builds a new class from an existing one. The subclass gets every method of the superclass and adds or changes what it needs. Read class SavingsAccount < BankAccount as “a SavingsAccount is a special kind of BankAccount”.
savings_account.rb
class SavingsAccount < BankAccount
def initialize(rate)
super() # let BankAccount set up the balance (parentheses: pass nothing)
@interest_rate = rate # then add what is new
end
# Adds the earned interest to the balance.
def add_interest
interest = balance * @interest_rate / 100
deposit(interest) # inherited methods, called on self
end
endOverriding
class CheckingAccount < BankAccount
def initialize
super()
@transaction_count = 0
end
def deposit(amount) # same name: replaces the inherited one
@transaction_count += 1
super # bare super passes the same arguments along
end
def to_s
"CheckingAccount(balance=#{balance}, transactions=#{@transaction_count})"
end
endThe rules
- Call
superin the subclassinitialize, or the superclass’s instance variables never get set. superwith no parentheses passes all the current arguments;super()passes none;super(x)passes exactly x.- Instance variables are inherited: the subclass can read
@balancedirectly. Prefer the superclass’s methods anyway, so it can change its insides later. - Every class ultimately inherits from
Object, which is whereto_s,==,inspectand friends come from.
Mistakes to watch for
- Leaving
superout of the subclassinitialize:@balanceis never set, and the firstdepositfails inside the superclass withundefined method `+' for nil (NoMethodError). The line number points atBankAccount, but the bug is in the subclass. - Writing bare
superindef initialize(rate): it forwardsrateto aBankAccount#initializethat takes nothing, so you getwrong number of arguments (given 1, expected 0) (ArgumentError). Writesuper()with empty parentheses when the parent takes no arguments. - Misspelling
initialize(sayinitalize) raises nothing: Ruby simply never calls it, and every instance variable isnil. If a class “ignores” its constructor, check the spelling first.
Polymorphism and Duck Typing
accounts = [BankAccount.new(100), SavingsAccount.new(2.5), CheckingAccount.new]
accounts.each do |acct|
acct.deposit(10) # the version that runs depends on the actual object
puts acct # each class's own to_s
end
accounts.each do |acct|
acct.add_interest if acct.is_a?(SavingsAccount) # only savings accounts have this
end
# or ask about the method instead of the class:
accounts.each { |acct| acct.add_interest if acct.respond_to?(:add_interest) }BankAccount(balance=110.00)
BankAccount(balance=10.00)
CheckingAccount(balance=10.0, transactions=1)Read the second line carefully: SavingsAccount never defined to_s, so it inherits BankAccount’s and prints as one. CheckingAccount overrides both deposit (the count went to 1) and to_s. Which method runs is decided by the object’s class at the moment of the call, never by the name of the variable.
Duck typing
- Ruby does not check types when you call a method. Anything with a
depositmethod can go in that loop, related by inheritance or not: “if it walks like a duck…” respond_to?(:method)asks whether an object can do something, which is usually a better question than what class it is.- Use
is_a?(true for subclasses too) rather thanobj.class == SomeClass.
Modules as mixins
module Describable
def describe
"#{name} with area #{format('%.2f', area)}"
end
end
class Circle
include Describable # the module's methods become instance methods
attr_reader :name, :r
def initialize(r)
@name = "circle"
@r = r
end
def area
3.14159 * r ** 2
end
end
Circle.new(2).describe # "circle with area 12.57"
# A class has ONE superclass but may include MANY modules.
# Comparable and Enumerable are the two mixins everyone uses.Abstract-Style Base Classes and Equality
A base class that insists
class Shape
def initialize(name)
@name = name
end
def area
raise NotImplementedError, "#{self.class} must define area"
end
def describe
"#{@name} with area #{area}"
end
end
class Square < Shape
def initialize(side)
super("square")
@side = side
end
def area
@side * @side
end
end
Shape.new("x").describe # NotImplementedError
Square.new(3).describe # "square with area 9"Equality and hashing
class Point
attr_reader :x, :y
def initialize(x, y)
@x, @y = x, y
end
def ==(other)
other.is_a?(Point) && x == other.x && y == other.y
end
alias eql? == # needed for hash keys and Set membership
def hash
[x, y].hash
end
end- Ruby has no
abstractkeyword; raisingNotImplementedErrorin the base method is the convention. - Without
==, two objects are equal only if they are the very same object (equal?). - If you define
==, defineeql?andhashthe same way, or the objects will not behave in aHashorSet. Struct.new(:x, :y)gives youinitialize, accessors,==,hashandto_sfor free when a class is just a bundle of values.
Recursion
Objects and Algorithms · Ruby 1
A Method That Calls Itself
A recursive method solves a problem by solving a smaller version of the same problem, then doing one more step. Every recursion needs two things: a base case answered directly, and a recursive case that moves toward the base case.
Factorial
def factorial(n)
return 1 if n <= 1 # base case
n * factorial(n - 1) # recursive case: smaller n
end
# factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * 2 * 1 = 24Sum of digits
def digit_sum(n)
return n if n < 10
digit_sum(n / 10) + n % 10
end
# digit_sum(1729) = digit_sum(172) + 9 = (digit_sum(17) + 2) + 9 = ((1 + 7) + 2) + 9 = 19Palindrome
def palindrome?(s)
return true if s.length <= 1
return false if s[0] != s[-1]
palindrome?(s[1..-2])
endpalindrome?("racecar") # true
palindrome?("ab") # false: "a" != "b"
palindrome?("") # true: the empty string is its own reverseHow to write a recursive method, step by step
- 1. Say what the method returns for any input, in one sentence: “
factorial(n)returns n!”, “palindrome?(s)returns true if s reads the same backwards”. - 2. Write the base case first and
returnfrom it: the smallest input you can answer without thinking (n <= 1, an empty or one-character string, an empty array). - 3. Shrink the input by at least one step toward that base case:
n - 1,s[1..-2],n / 10. If the input does not get smaller, the recursion never ends. - 4. Call the method on the smaller input and trust the answer, because of step 1.
- 5. Combine that answer with the one piece you kept back: multiply by
n, addn % 10, compare the first and last letters. - 6. Test the base case alone, then one step above it (
factorial(1), thenfactorial(2)). If those two are right, the rest follows.
Thinking recursively
- Trust the recursive call. Assume
palindrome?works for shorter strings; your job is only the first and last letter. - Make sure each call is strictly smaller and that the smallest case is handled before any recursive call.
- Trace tiny inputs by hand: the empty string, one character, two characters.
When Recursion Is Slow
# Fibonacci the obvious way: correct, but fib(35) makes about 30 million calls
def fib(n)
return 1 if n <= 2
fib(n - 1) + fib(n - 2)
end
# The same numbers with a loop: n steps
def fib_loop(n)
older, old = 1, 1
(n - 2).times { older, old = old, older + old }
old
end
# Or remember answers you already have (memoization) in a hash
FIB = Hash.new { |h, n| h[n] = n <= 2 ? 1 : h[n - 1] + h[n - 2] }
FIB[80] # 23416728348467685- When the recursive case calls itself twice on overlapping problems, the work doubles at every level. Use a loop or memoization.
- Each call uses a stack frame. Ruby stops at roughly ten thousand levels with
SystemStackError: stack level too deep; a loop would not. - Recursion shines when the problem is naturally nested: permutations, subsets, folders inside folders, trees, and “try every choice” searches.
Permutations and Towers of Hanoi
All permutations of a string
def permutations(word)
return [""] if word.empty? # one permutation of the empty string
result = []
word.each_char.with_index do |ch, i|
shorter = word[0...i] + word[(i + 1)..]
permutations(shorter).each { |p| result << ch + p }
end
result
end
p permutations("eat")
# ["eat", "eta", "aet", "ate", "tea", "tae"]
# (the library has it too: "eat".chars.permutation.map(&:join))Towers of Hanoi
# Moves n disks from source to target using spare.
def hanoi(n, source, target, spare)
return if n == 0
hanoi(n - 1, source, spare, target)
puts "Move disk #{n} from #{source} to #{target}"
hanoi(n - 1, spare, target, source)
end
hanoi(3, "A", "C", "B") # 7 moves; n disks take 2**n - 1Mutual recursion is two methods that call each other, such as an expression evaluator where expression calls term, which calls factor, which calls expression again for a parenthesized part. The base case is still a method that returns without calling the other.
Sorting and Searching
Objects and Algorithms · Ruby 1
Selection Sort and Insertion Sort
Selection sort
def selection_sort(values)
n = values.length
(0...n - 1).each do |i|
min_pos = i # find the smallest in values[i..]
(i + 1...n).each do |j|
min_pos = j if values[j] < values[min_pos]
end
values[i], values[min_pos] = values[min_pos], values[i] # swap it into place
end
endInsertion sort
def insertion_sort(values)
(1...values.length).each do |i|
next_value = values[i] # values[0...i] is already sorted
j = i
while j > 0 && values[j - 1] > next_value
values[j] = values[j - 1] # slide bigger ones right
j -= 1
end
values[j] = next_value # drop it into the gap
end
end# insertion_sort([5, 3, 8, 1]), printing values at the end of each pass:
after i = 1: [3, 5, 8, 1] # 3 slid left past 5
after i = 2: [3, 5, 8, 1] # 8 was already in place: no moves
after i = 3: [1, 3, 5, 8] # 1 slid left past 8, 5 and 3To see a trace like this yourself, add p values as the last line inside the outer each. The invariant to check at every pass is that values[0..i] is sorted; the part to the right is still untouched.
Both make about n²/2 comparisons: doubling the array quadruples the time. Insertion sort is fast on data that is already nearly sorted; selection sort always does the same work. Both change the array they are given, so by Ruby convention they would be named selection_sort!.
Merge Sort
def merge_sort(values)
return values if values.length <= 1
mid = values.length / 2
first = merge_sort(values[0...mid]) # sort each half
second = merge_sort(values[mid..])
merge(first, second) # then merge them
end
def merge(first, second)
merged = []
i = j = 0
while i < first.length && j < second.length
if first[i] < second[j]
merged << first[i]
i += 1
else
merged << second[j]
j += 1
end
end
merged.concat(first[i..]).concat(second[j..]) # whatever is left over
end
# returns a NEW sorted array: sorted = merge_sort(values)| Algorithm | Comparisons for n items | Big-O | Doubling n makes it |
|---|---|---|---|
| Selection sort | about n²/2 | O(n²) | 4 times slower |
| Insertion sort | n²/4 average; n if already sorted | O(n²) | 4 times slower |
| Merge sort | about n log2 n | O(n log n) | a little more than 2 times slower |
Ruby’s sort (quicksort) | n log n on average | O(n log n) | a little more than 2 times slower |
| Linear search | n/2 average, n worst | O(n) | 2 times slower |
| Binary search (sorted data) | about log2 n | O(log n) | one more step |
Big-O keeps only the fastest-growing term and drops constants: 3n² + 20n + 7 is O(n²). It describes how the work scales, not how many seconds it takes.
Searching
Linear search
def linear_search(values, target)
values.each_with_index do |v, i|
return i if v == target
end
nil
end
# built in: values.index(target), values.include?(target), values.find { |v| ... }Binary search (the array must be sorted)
def binary_search(values, target)
low = 0
high = values.length - 1
while low <= high
mid = (low + high) / 2
if values[mid] == target
return mid
elsif values[mid] < target
low = mid + 1
else
high = mid - 1
end
end
nil
end
# 1,000,000 sorted items: at most 20 steps
p binary_search([1, 3, 5, 7, 9, 11], 7) # 3
p binary_search([1, 3, 5, 7, 9, 11], 4) # nil: low passes high, the loop ends
# mid = (low + high) / 2 is integer division, so mid is always a valid indexThe library does it faster: use these in real programs
values.sort # a sorted copy, ascending
values.sort! # in place
values.sort.reverse # descending
values.max(3) # the three largest
names.sort_by { |n| n.length } # by another rule
names.sort_by(&:downcase) # case-insensitive
people.sort_by { |p| [p.last, p.first] } # by two keys
people.sort { |a, b| b.age <=> a.age } # custom comparison, descending age
values.bsearch { |v| v >= 42 } # binary search in the library (sorted data)Sorting your own objects
class Country
include Comparable
attr_reader :name, :area
def initialize(name, area)
@name, @area = name, area
end
def <=>(other) # the natural order: -1, 0 or 1
area <=> other.area
end
end
countries.sort # uses <=>
countries.min # so do min, max and between?
countries.sort_by(&:name) # or any other order, by keysort_by vs <=>
<=>(the “spaceship”) in the class gives one natural order thatsort,min,maxandComparableall use.sort_bypicks a different order for one call without touching the class. Its block receives each item and returns what to compare, and it is faster thansortwith a block because each key is computed once.sort_byis stable only by accident; if ties matter, add a second key:sort_by { |p| [p.age, p.name] }.