Small values, carefully designed
Every program is built from small values: numbers, pieces of text, names, true and false. How a language treats them decides a surprising amount of everyday experience. Does 7 / 2 give 3 or 3.5? Is 0 true or false? Can a function change a string you passed it? Is "São Paulo" nine characters or ten?
Ruby's answers are consistent, mostly unsurprising, and in a couple of places different from the languages you may know. This lesson goes through them with code you can run, then covers Ruby's control flow, where one idea ties everything together: in Ruby, almost everything is an expression that returns a value, including if, case and even loops.
Numbers
Ruby's main numeric classes are Integer (whole numbers of any size), Float (64-bit binary floating point), Rational (exact fractions, written with an r suffix) and, from the standard library, BigDecimal (exact decimals). Complex exists too.
require "bigdecimal"
# Integer division rounds down (toward negative infinity), and % follows the divisor's sign.
p 7 / 2, -7 / 2, 7 % 3, -7 % 3, 7.divmod(2)
# Mix in a float, or ask for one, to get a fractional result.
p 7.0 / 2, 7.fdiv(2), 2**64, 10**-2
# Floats are binary approximations; Rational and BigDecimal are exact.
p 0.1 + 0.2, 0.1 + 0.2 == 0.3
p 0.1r + 0.2r == 0.3r, 1/3r + 1/6r
p BigDecimal("0.1") + BigDecimal("0.2") == BigDecimal("0.3")
# Rounding: halves round away from zero by default.
p 2.5.round, 3.5.round, -2.5.round, 2.5.round(half: :even), 3.14159.round(2), 3.7.floor, 3.2.ceil
# Converting text to numbers: strict and forgiving.
p Integer("42"), Integer("4x2", exception: false), "4x2".to_i, "12 apples".to_i, Float("2.5")
begin
Integer("twelve")
rescue ArgumentError => e
puts "ArgumentError: #{e.message}"
end3
-4
1
2
[3, 1]
3.5
3.5
18446744073709551616
(1/100)
0.30000000000000004
false
true
(1/2)
true
3
4
-3
2
3.14
3
4
42
nil
4
12
2.5
ArgumentError: invalid value for Integer(): "twelve"The details worth remembering:
- Integer division floors.
7 / 2is 3, and-7 / 2is −4, not −3: Ruby rounds toward negative infinity, and%gives a result with the divisor's sign, so-7 % 3is 2.divmodreturns both at once. (C, Java and PHP truncate toward zero instead, so this is a classic surprise when translating code.) - Get a fractional result by making one operand a float (
7.0 / 2) or withfdiv. And note that an integer raised to a negative power gives an exactRational:10**-2is(1/100). - Floats are approximations, exactly as in every language that uses IEEE 754:
0.1 + 0.2is not0.3. For exact fractions, useRational(0.1rmeans exactly one tenth). For money and other decimal quantities, use integers of the smallest unit orBigDecimal, which Rails uses for decimal database columns. - Rounding sends halves away from zero (
2.5.roundis 3,-2.5.roundis −3). Passhalf: :evenfor banker's rounding, which statistics and some financial rules require. - Converting text.
Integer("42")is strict: it raisesArgumentErrorfor anything that is not entirely an integer, or returnsnilif you passexception: false."12 apples".to_iis forgiving: it reads as many digits as it can and returns 0 if there are none. Use the strict form for anything a person typed; useto_ionly when you already trust the text. - Underscores make large literals readable:
1_000_000.
Strings and symbols
A Ruby string is a sequence of characters in a known encoding, almost always UTF-8. Unlike some languages, Ruby counts, slices and changes case by character, not by byte.
# frozen_string_literal: true
city = "São Paulo"
p city.length, city.bytesize, city.upcase, city.reverse
p city[0, 3], city[-5..], city.include?("Paulo"), city.start_with?("Sã")
p city.sub("São", "Santo"), city.split, city.chars.first(3)
# With the magic comment above, string literals are frozen. Use +"" or .dup for a mutable copy.
p city.frozen?
name = +"Ana"
name << " Lima"
puts name
# Formatting.
puts format("%-8s|%6.2f|%03d", "tea", 4.5, 7)
puts "Total: #{'%.2f' % 1234.5}"
puts "Hi, %s! You have %d messages." % ["Kofi", 3]
# A squiggly heredoc strips the common indentation.
menu = <<~TEXT
Today:
- jollof rice
- pho
TEXT
puts menu
# Symbols: immutable names, one object per name.
p :pending.equal?(:pending), "pending".dup.equal?("pending".dup)
p :pending.to_s, "paid".to_sym, %i[low normal high]
labels = { pending: "Waiting for payment", paid: "Paid" }
p labels[:paid], labels.keys9
10
"SÃO PAULO"
"oluaP oãS"
"São"
"Paulo"
true
true
"Santo Paulo"
["São", "Paulo"]
["S", "ã", "o"]
true
Ana Lima
tea | 4.50|007
Total: 1234.50
Hi, Kofi! You have 3 messages.
Today:
- jollof rice
- pho
true
false
"pending"
:paid
[:low, :normal, :high]
"Paid"
[:pending, :paid]Character-aware. "São Paulo".length is 9 characters, while bytesize is 10, because ã takes two bytes in UTF-8. Slicing (city[0, 3], the first three characters; city[-5..], the last five) and upcase work on characters, so the accented letter survives. You rarely need to think about bytes in Ruby unless you are reading binary files or network protocols.
Frozen string literals. Ruby strings are mutable: methods like << and those ending in ! (such as upcase!) change the string in place. That is efficient but risky, because two variables can refer to the same string. The comment on the first line, # frozen_string_literal: true, is a magic comment that makes every string literal in the file frozen (immutable); modifying one raises FrozenError. Most Ruby style guides ask for it in every file. When you do want a mutable string, write +"Ana" or "Ana".dup. The language is moving towards frozen literals by default: since Ruby 3.4, literals in files without the comment are "chilled", which means they still work when modified but produce a deprecation warning when warnings are enabled (we ran such a program with deprecation warnings switched on, and Ruby 4.0 printed warning: literal string will be frozen in the future).
Formatting. format (also called sprintf) and the % operator on strings use C-style directives: %-8s left-aligns in 8 columns, %6.2f is width 6 with two decimals, %03d pads with zeros. Inside interpolation you can call any method, so "#{'%.2f' % total}" is common.
Heredocs. <<~TEXT … TEXT is a multi-line string. The ~ ("squiggly heredoc") removes the indentation common to all lines, so the text can be indented with the code around it while the result keeps only the relative indentation.
Symbols. A symbol such as :pending is an immutable, interned name: there is exactly one :pending object in the whole program, so comparing two symbols is as fast as comparing two integers. That is what equal? (same object) shows: two :pending are the same object, while two strings built separately are not. Symbols are used where you mean a name rather than some text: hash keys, method names (send(:upcase)), options (round(half: :even)), states. { pending: "…" } is shorthand for { :pending => "…" }, the most common hash form in Ruby. %i[low normal high] makes an array of symbols, as %w[…] makes one of strings. Convert with to_s and to_sym, but avoid turning arbitrary user input into symbols.
Ranges, equality and ordering
Two more kinds of value appear in almost every Ruby program: ranges, and the comparisons that decide whether two values are equal or which comes first.
# Ranges: two dots include the end, three dots exclude it.
p (1..5).to_a, (1...5).to_a, ("a".."e").to_a.join
p (1..10).sum, (1..10).step(3).to_a, 10.downto(7).to_a
# Endless and beginless ranges.
adult = (18..) # parentheses: a bare "18.." would continue onto the next line
p adult.include?(42), (..0).include?(-3)
# include? vs cover? for strings: membership in the sequence, or between the ends.
p ("a".."z").include?("bb"), ("a".."z").cover?("bb")
# Comparisons: == compares values, equal? asks "same object?", <=> orders.
a = "kiwi"
b = "kiwi".dup
p a == b, a.equal?(b), a.equal?(a)
p 1 == 1.0, 1.eql?(1.0), 3 <=> 5, "b" <=> "a", [1, 2] <=> [1, 3]
p 15.between?(10, 20), 25.clamp(0, 20), 7.clamp(..5)[1, 2, 3, 4, 5]
[1, 2, 3, 4]
"abcde"
55
[1, 4, 7, 10]
[10, 9, 8, 7]
true
true
false
true
true
false
true
true
false
-1
1
-1
true
20
5Definition— Range
A pair of endpoints, written a..b (including b) or a...b (excluding b). Ranges work for anything that can be ordered: integers, strings, dates. (18..) is an endless range and (..0) a beginless one. Ranges are objects with methods: sum, step, to_a, include?, each. Note the parentheses around (18..): without them, Ruby reads the next line as the end of the range, a real surprise when it happens.
include? and cover? differ for strings. cover? asks "is this value between the ends?", and "bb" sorts between "a" and "z". include? on a string range asks "is this one of the values the range would produce?", and "a".."z" produces only single letters. For numbers the two agree.
Definition— Equality and identity
== compares values and is what you almost always want. equal? asks whether two references are the very same object (identity). eql? is stricter than == about types, which is why 1 == 1.0 is true but 1.eql?(1.0) is false; hashes use eql? to compare keys. And === is the "case equality" used by case/when, which you will see next.
Definition— The spaceship operator
a <=> b returns −1, 0 or 1 when a is less than, equal to or greater than b (and nil when they cannot be compared). Sorting is built on it, and any class that defines <=> and includes the Comparable module gets <, >, between? and clamp for free, as numbers and strings do. Arrays compare element by element, which makes sorting by several keys easy.
Decisions and loops
# Only nil and false are falsy. 0, "" and [] are all truthy.
[0, "", [], nil, false, "false"].each do |value|
puts "#{value.inspect.ljust(7)} #{value ? 'truthy' : 'falsy'}"
end
def describe(celsius)
case celsius
when ...0 then "freezing"
when 0...15 then "cool"
when 15...25 then "mild"
when 25...35 then "hot"
else "dangerously hot"
end
end
def kind(value)
case value
when Integer, Float then "a number"
when /\A\d+\z/ then "a string of digits"
when String then "some other string"
when nil then "nothing at all"
else "a #{value.class}"
end
end
puts [-4, 12, 24, 31, 41].map { |t| "#{t}°C #{describe(t)}" }.join(", ")
puts [42, "2026", "hello", nil, :sym].map { |v| kind(v) }.inspect
# if is an expression: it returns a value.
score = 72
grade = if score >= 90 then "A" elsif score >= 70 then "B" else "C" end
puts "grade #{grade}"
# Modifiers put a short condition after the statement.
puts "even" if score.even?
puts "has items" unless [].empty?
# until is "while not". This counts Collatz steps from 27 to 1.
n = 27
steps = 0
until n == 1
n = n.even? ? n / 2 : 3 * n + 1
steps += 1
end
puts "27 reaches 1 after #{steps} steps"
# loop runs forever until break, and break can return a value.
attempt = 0
found = loop do
attempt += 1
next if attempt.odd?
break attempt * 10 if attempt > 3
end
puts "found #{found} after #{attempt} attempts"
# Safe navigation and ||=
user = nil
p user&.upcase
settings = {}
settings[:timeout] ||= 30
settings[:timeout] ||= 60
p settings0 truthy
"" truthy
[] truthy
nil falsy
false falsy
"false" truthy
-4°C freezing, 12°C cool, 24°C mild, 31°C hot, 41°C dangerously hot
["a number", "a string of digits", "some other string", "nothing at all", "a Symbol"]
grade B
even
27 reaches 1 after 111 steps
found 40 after 4 attempts
nil
{timeout: 30}Truthiness. In Ruby only two values are falsy: nil and false. Everything else is truthy, including 0, the empty string and the empty array. This is simpler than the rules in JavaScript, Python or PHP, but it surprises people coming from them: if count is true even when count is 0. Ask what you mean: count.zero?, name.empty?, list.any?.
case/when compares the value against each when using the === operator, which each class defines in a useful way. For a range, === means "is included in" (when 0...15; three dots exclude the end, two include it, and ...0 is a range with no beginning). For a class, it means "is an instance of" (when Integer). For a regular expression, it means "matches" (when /\A\d+\z/). You can list several values in one when. There is no fall-through between when branches. The next-but-one lesson adds case/in pattern matching, a more powerful relative.
Everything is an expression. grade = if … elsif … else … end assigns whatever branch ran. A method returns its last expression, so describe needs no return: the case is the result.
Modifiers and unless. puts "even" if score.even? puts a short condition after a statement; unless means "if not". Use unless only for simple, positive conditions: unless x.nil? reads well, but unless with an else or with ! inside confuses everyone.
Loops. while and until (the opposite of while) exist, and the Collatz loop uses until n == 1. But idiomatic Ruby rarely needs them: iteration over collections uses methods with blocks (each, map, times), the subject of the next lessons. loop do … end repeats forever until break, and break value makes the whole loop expression return that value; next skips to the next iteration. There is a for loop as well, which experienced Rubyists avoid in favour of each.
Two small operators. user&.upcase is safe navigation: if user is nil, the call is skipped and the result is nil, instead of raising NoMethodError. settings[:timeout] ||= 30 assigns only if the current value is falsy (nil or false), so the second ||= 60 does nothing. It is the standard idiom for defaults and caches. Because false is falsy too, do not use ||= for a setting that may legitimately be false.
Note
Living with nil. Many Ruby methods return nil to mean "nothing here": [].first, {}[:missing], "abc".index("z"), a case with no matching branch and no else, an if whose condition was false and has no else. That is convenient, and it is also the source of Ruby's most common runtime error, NoMethodError: undefined method … for nil, which usually appears far from the line that produced the nil. Experienced Rubyists reduce it in a few ways: they use methods that fail loudly when a value must exist (hash.fetch(:key) raises KeyError with the missing key's name, while hash[:key] silently returns nil); they supply defaults at the boundary (fetch(:key, 30), name.to_s, Array(maybe_list)); they use &. only where nil is a genuinely expected value, not to paper over a bug; and they check method results close to where they are produced. The type-checking tools you will meet in the last lesson can also track which values may be nil.
Common misunderstandings
Misconception
"0 and "" are false, as in other languages." In Ruby they are true. Only nil and false are falsy. Code such as puts "no items" unless items.size never prints anything; write if items.empty?.
Misconception
"-7 / 2 is −3." Ruby's integer division rounds toward negative infinity, so it is −4, and -7 % 3 is 2. If you need truncation toward zero, use (-7).fdiv(2).truncate or -7.remainder(3) for the remainder, and say so in a comment.
Misconception
"Strings and symbols are interchangeable." { name: "Ana" }[:name] finds the value, but { name: "Ana" }["name"] returns nil, because the string "name" and the symbol :name are different keys. Data parsed from JSON has string keys unless you ask for symbols (JSON.parse(text, symbolize_names: true)). Rails hides this difference in some places, which makes it more confusing, not less.
Misconception
"x ||= y is the same as x = x || y, so it always assigns." It is closer to x || (x = y): if x is already truthy, no assignment happens at all. That matters for hashes with defaults and for objects that track changes. And it treats false as missing.
Exercises
1. Values, strings, symbols and control flow
Warm-upComputationalWhat does this line print?
puts [-7 / 2, -7 % 3].inspect
2. Values, strings, symbols and control flow
Warm-upComputationalWhat does this print?
puts [0, "", nil, false, [], "nil", 0.0].count { |v| v }
3. Values, strings, symbols and control flow
CoreComputationalWhat does this program print?
def size(n)
case n
when 0 then "none"
when 1..3 then "few"
when Integer then "many"
else "?"
end
end
puts [0, 2, 10, 2.5].map { size(it) }.join(",")
4. Values, strings, symbols and control flow
CoreComputationalThe file is UTF-8. What does this print?
puts "São".length.to_s + "São".bytesize.to_s
5. Values, strings, symbols and control flow
CoreComputationalWhat does this program print?
x = nil
x ||= 5
x ||= 7
y = false
y ||= 9
puts [x, y].inspect
6. Values, strings, symbols and control flow
CoreComputationalGiven prices = { tea: 4, coffee: 5 }, what is prices["tea"]?
7. Values, strings, symbols and control flow
StretchComputationalWhat does this print?
p [2.5.round, -2.5.round, 2.5.round(half: :even)]
Further reading and resources
- Ruby docs: Integer
- Ruby docs: StringEvery string method, with examples.
- Ruby docs: Symbol
- Ruby docs: Control expressionsif, unless, case, while, until, loop and their modifiers.
- Ruby docs: format specificationsThe directives understood by format, sprintf and String#%.