Variables and Core Types

Variables and Core Types in Ruby: At the cloakroom of an old concert hall you hand your coat across the counter and receive a brass tag stamped 214.

The Analogy: The Coat Check Counter And Its Brass Tags

At the cloakroom of an old concert hall you hand your coat across the counter and receive a brass tag stamped 214. The attendant hangs the coat on rail two, position fourteen, and that is the last you see of it until the interval. The tag is small, light, and completely interchangeable with any other tag except for the number on it. It is not a small coat. It is not a description of your coat. It is a claim on one particular garment hanging in a room you cannot enter.

Everything interesting about the arrangement follows from tags being cheap and coats being expensive. Your companion asks for a tag too, and the attendant stamps a second 214 rather than fetching a second coat: two tags, one garment. If your companion redeems their tag, walks the coat to a tailor and has a badge sewn onto the sleeve, then when you redeem yours at the interval you get a coat with a badge on it, because there was only ever one coat. But if your companion goes back to the counter and swaps their tag for number 87 on a different coat, nothing at all happens to yours. Altering the garment and re-pointing the tag look similar when you are holding brass, and they are not remotely the same act.

Ruby variables are the brass tags. name = "gauge block" hangs a String in the object space and stamps your tag with the number that finds it. label = name stamps a second tag with the same number, so label.equal?(name) is true and no second string was built. label << " A2" is the badge on the sleeve: it reaches through the tag and modifies the one garment, so name shows the change too. label = "shim" is the swap at the counter: your tag now finds something else and the original is untouched. Some items are behind glass rather than on a rail, sealed by the hall and impossible to alter: integers, symbols, nil, true and false cannot be modified in place by anybody, so for those the distinction never bites.

The failure mode is the shared garment nobody realised was shared. A cloakroom that offers "a copy of your coat" and hands over a copy of the tag will run for years without complaint, because most patrons only ever look at their coat. The bug appears the first time two people hold tags for one garment and one of them alters it, and it appears at the second person's counter visit rather than at the tailor's, which is a long way from the cause. Ruby's version of this is a default value stored in a constant and handed to every caller, one of whom appends to it and permanently changes what "default" means for the rest of the run. The second half of the trap is that copying is shallower than it looks: duplicate the coat and you get a new coat holding the same objects in its pockets, so anything reachable through those pockets is still shared.


Syntax or Core Structure

There are no type declarations and no declaration keyword. Assignment creates the name, and the name is untyped: it holds whatever it was last pointed at. What determines the kind of thing you have is the literal you wrote, and Ruby has a literal for every core type.

# types.rb

count     = 42                    # Integer
ratio     = 0.75                  # Float
name      = "gauge block"         # String
state     = :calibrated           # Symbol
present   = true                  # TrueClass
missing   = nil                   # NilClass
sizes     = [3, 8, 12]            # Array
limits    = { min: 3, max: 12 }   # Hash
span      = (3..12)               # Range
MM_PER_IN = 25.4                  # Constant, marked only by its capital letters

values = [count, ratio, name, state, present, missing, sizes, limits, span]
values.each { |v| puts v.class }

puts name.length
puts sizes.sum
puts limits[:max]
puts span.include?(7)
puts MM_PER_IN * 2

Output:

Integer
Float
String
Symbol
TrueClass
NilClass
Array
Hash
Range
11
23
12
true
50.8

Four conventions in that file are enforced by the interpreter rather than by taste. A name beginning with a lower case letter or an underscore is a local variable. A name beginning with a capital is a constant, and reassigning one produces a warning rather than an error, which is Ruby telling you it noticed but declining to stop you. Underscores are legal inside numeric literals, so 1_000_000 is a million and easier to read. And a name is never annotated with a type, so the only way to know what you are holding is to ask it, which is why .class and .inspect are the two most used methods in the language.

The remaining sigils are about where a name can be seen rather than what it holds, and they matter as soon as you write a class:

COUNTER_LIMIT = 3   # constant: visible wherever the enclosing scope is
attempts      = 0   # local: visible here, and inside blocks written here
# @attempts         # instance: one per object, used inside its own methods
# @@attempts        # class: one shared by a class and all its subclasses
# $attempts         # global: visible in the whole process, almost never right

Three of those five are commented out because they are meaningless at the top level of a script. The two you will type constantly are locals and instance variables. @@ class variables are shared down an inheritance chain in a way that surprises people, and $ globals have no access control at all, so both are best treated as things you can recognise rather than things you reach for.


Technical Depth: Names, Objects, And The Types Underneath

A Name Is a Tag, Not a Box

The single most useful experiment in Ruby is four lines long. It separates mutation, which reaches through the tag, from reassignment, which re-points it.

a = "admin"
b = a

puts a.equal?(b)

b << "!"
puts a
puts b

b = "guest"
puts a
puts b
puts a.equal?(b)

puts :admin.frozen?
puts 42.frozen?
puts nil.frozen?
puts "admin".frozen?

Output:

true
admin!
admin!
admin!
guest
false
true
true
true
false

b << "!" printed admin! twice because there is one string with two tags on it. b = "guest" printed admin! and guest because the second assignment moved only b. The last four lines say which values can be caught out by this: symbols, integers and nil are frozen by the language and cannot be altered in place at all, while a plain string literal is mutable, which makes strings the value you have to think about.

Where a Name Can Be Seen

FormKindWho can see itNotes
totallocal variablethe method, block or file scope that created itthe default, and what you should reach for
@totalinstance variableany method of that one objectreading one that was never set gives nil, not an error
@@totalclass variablethe class and every subclass, as one shared slota subclass assignment changes the parent's value too
$totalglobal variablethe entire processno access control at all, so essentially untestable
TOTALconstantits lexical scope, and anything that includes the modulereassigning warns but is permitted

The @total row hides a real trap: because an unset instance variable reads as nil rather than raising, a typo in @totl gives you a silent nil instead of a loud failure. Running with ruby -w reports it, which is most of the reason to use that flag.

The Core Types at a Glance

LiteralClassMutableWorth knowing
42Integernoarbitrary precision, so no overflow and no fixed width
0.75Floatnoan IEEE 754 double, inexact for most decimal fractions
1/3rRationalnoan exact fraction, printed as a numerator over a denominator
"text"Stringyesthe mutable value you will actually meet in practice
:textSymbolnoan interned name, one object per distinct name
trueTrueClassnofalse and nil are the only two values a condition treats as untrue
nilNilClassnoa real object with methods, and the sole instance of its class
[3, 8]Arrayyesordered, may mix types freely
{ min: 3 }Hashyeskeeps insertion order, and a default value can be supplied
(3..12)Rangenowrite three dots to exclude the end value

Integers Never Overflow, Floats Never Quite Add Up

Ruby's integers grow into arbitrary precision automatically, so there is no 32 bit or 64 bit ceiling to plan around. Floats behave the way floats behave everywhere, and Ruby gives you two exact alternatives when that is not acceptable.

big = 2 ** 100
puts big
puts big.class

puts 7 / 2
puts -7 / 2
puts 7 % 3
puts -7 % 3
puts 7.fdiv(2)
puts 7.divmod(2).inspect

sum = 0.1 + 0.2
puts sum
puts sum == 0.3
puts sum.round(2) == 0.3
puts Rational(1, 10) + Rational(2, 10) == Rational(3, 10)

exact = 0.1r + 0.2r
puts exact == 0.3r

Output:

1267650600228229401496703205376
Integer
3
-4
1
2
3.5
[3, 1]
0.30000000000000004
false
true
true
true

Two of those results catch people out for different reasons. 7 / 2 is 3 because dividing two integers gives an integer, and the fix is fdiv or making one side a float rather than adding a cast at the end. -7 / 2 is -4 rather than -3 because Ruby floors toward negative infinity instead of truncating toward zero, and -7 % 3 is 2 rather than -1 for the same reason: the remainder takes the sign of the divisor. If you need the C or Java behaviour, remainder gives it, and mixing the two up in a hashing or wrap-around calculation produces a bug that only appears for negative inputs.

Freezing Is Shallow, And So Is dup

DEFAULT_TAGS = ["urgent", "review"].freeze

puts DEFAULT_TAGS.frozen?
puts DEFAULT_TAGS.first.frozen?

copy = DEFAULT_TAGS.dup
puts copy.frozen?
copy << "extra"
puts copy.length
puts DEFAULT_TAGS.length

twin = DEFAULT_TAGS.clone
puts twin.frozen?

nested = [["a"], ["b"]].freeze
shallow = nested.dup
shallow[0] << "changed"
puts nested[0].inspect

Output:

true
false
false
3
2
true
["a", "changed"]

Three rules are visible there. freeze protects the container and not its contents, so the frozen array still holds two mutable strings. dup produces an unfrozen copy and clone preserves the frozen state, which is the practical difference between them. And the last two lines are the trap worth remembering: shallow is a new array, but its slot zero holds the very same inner array as the frozen original, so mutating through the copy modified something declared frozen. Nothing in the language stopped it, because nothing was violated.

Conversion Has a Lenient Mode and a Strict Mode

The lenient methods answer with a number no matter what you hand them. The strict functions, spelled with a capital letter because they are methods on Kernel, refuse.

Applied toto_ito_fInteger()Float()
"42"4242.04242.0
"42abc"4242.0raises ArgumentErrorraises ArgumentError
"4.9"44.9raises ArgumentError4.9
""00.0raises ArgumentErrorraises ArgumentError
nil00.0raises TypeErrorraises TypeError

The row for the empty string is the one that causes production incidents. A missing form field arrives as "", to_i turns it into a perfectly plausible zero, and that zero is stored as a quantity, a price or a limit. Use the strict form at the boundary where outside data enters, and keep to_i for cases where you have already decided that a missing value genuinely means zero.


Real World Example: An Exact Gauge Log

Inspection readings arrive as text, in two different units, and end up in a report that a supervisor signs. Every type decision in the program below is about not letting the text turn into a number that is merely close.

# gauge_log.rb -- turn raw gauge readings into an exact shift summary.

MM_PER_INCH = Rational(254, 10)

RAW = [
  ["reamer-3-8",  "12.70",  "mm"],
  ["mic-0-1",     "0.500",  "in"],
  ["endmill-6mm", "6.02",   "mm"],
  ["gauge-block", "1.0000", "in"],
  ["reamer-3-8",  "12.68",  "mm"],
]

Reading = Struct.new(:tool, :raw, :unit, :mm)

def to_mm(text, unit)
  exact = Rational(text)
  unit == "in" ? exact * MM_PER_INCH : exact
end

readings = RAW.map { |tool, raw, unit| Reading.new(tool, raw, unit, to_mm(raw, unit)) }

puts "readings: #{readings.size}"
readings.each do |r|
  puts "  #{r.tool.ljust(12)}#{r.raw.rjust(7)} #{r.unit}  exact #{r.mm}  float #{r.mm.to_f}"
end

total = readings.sum(Rational(0)) { |r| r.mm }
mean  = total / readings.size

puts "total exact #{total}  float #{total.to_f}"
puts "mean  exact #{mean}  float #{mean.to_f}"

float_total = readings.map { |r| r.mm.to_f }.inject(:+)
puts "float path total #{float_total}"
puts "paths agree: #{float_total == total.to_f}"

widest    = readings.max_by(&:mm)
narrowest = readings.min_by(&:mm)
puts "widest    #{widest.tool} at #{widest.mm.to_f} mm"
puts "narrowest #{narrowest.tool} at #{narrowest.mm.to_f} mm"

# Where the lenient conversions quietly invent a measurement.
["12.70", "12.7mm", "", "twelve"].each do |text|
  strict = begin
    Float(text)
  rescue ArgumentError
    "rejected"
  end
  puts "#{text.inspect.ljust(10)} to_f #{text.to_f}  Float() #{strict}"
end

Output:

readings: 5
  reamer-3-8    12.70 mm  exact 127/10  float 12.7
  mic-0-1       0.500 in  exact 127/10  float 12.7
  endmill-6mm    6.02 mm  exact 301/50  float 6.02
  gauge-block  1.0000 in  exact 127/5  float 25.4
  reamer-3-8    12.68 mm  exact 317/25  float 12.68
total exact 139/2  float 69.5
mean  exact 139/10  float 13.9
float path total 69.5
paths agree: true
widest    gauge-block at 25.4 mm
narrowest endmill-6mm at 6.02 mm
"12.70"    to_f 12.7  Float() 12.7
"12.7mm"   to_f 12.7  Float() rejected
""         to_f 0.0  Float() rejected
"twelve"   to_f 0.0  Float() rejected

The storage decision is the whole program. Rational(text) parses the decimal string into an exact fraction, so "12.70" becomes 127 over 10 and stays that ratio through every later operation. Converting inches multiplies by Rational(254, 10), which is the inch defined exactly rather than approximated, so half an inch comes out as 127 over 10 millimetres and not as something ending in a drift of digits. Struct.new gives each row four named readers, and keeping both the original raw text and the derived mm value means the report can always show what was written on the gauge sheet next to what the program made of it.

Notice that paths agree printed true. That is a genuine result and it is also the least durable line in the output. It agrees because five readings summed to 69.5, which happens to be exactly representable as a double, and because the intermediate products were exact too. Add a reading of a third of a millimetre, or sum ten thousand rows, and the exact path stays exact while the float path accumulates error. The point of the exact path is not that it disagrees today, it is that its correctness does not depend on the data being lucky.

The last block is a demonstration of the same discipline applied to input rather than arithmetic. "12.7mm".to_f returns 12.7, which is almost certainly the right number arrived at by the wrong route, since nothing checked that the unit had already been handled. "".to_f returns 0.0, and a gauge reading of zero millimetres is a perfectly plausible value that a human will believe. Float() rejects both, and a rejection you can see is worth more than a number you cannot audit.

The honest limits start with a real design flaw in to_mm. The expression unit == "in" ? exact * MM_PER_INCH : exact treats every unit that is not exactly the string "in" as millimetres, so a row recorded in "cm", or in "IN", or with a trailing space after in, is silently multiplied by nothing and enters the report as a plausible millimetre figure that is wrong by a factor of ten or twenty five. A unit typo should be the loudest failure in a measurement program and here it is the quietest. Beyond that: Rational(text) raises on the first malformed reading and takes the whole report down without naming the row, so one bad line costs you all the good ones; max_by and min_by return an arbitrary winner when two readings tie, without saying so; the summary reports a mean over readings taken from different tools, which is a number with no physical meaning; and RAW is a constant in the source, so the program cannot yet read a real gauge sheet.


Common Mistakes

  1. Believing that assignment copies. b = a copies the tag, not the coat. Every mutating call through b is visible through a, which is fine when you intended sharing and a long hunt when you did not. If you want a separate object, say b = a.dup and then check whether the contents needed duplicating too.
  1. Treating a constant as immutable. The capital letters stop reassignment with a warning, and stop nothing else. SETTINGS = { retries: 3 } can be modified by any code that can see it. Write .freeze after the literal, and freeze the values inside it if they are containers as well.
  1. Using to_i and to_f on data from outside the program. They never fail, which sounds convenient until an empty form field becomes a quantity of zero and a mistyped "12,50" becomes twelve. Use Integer() and Float() at the boundary and let the error name the bad input.
  1. Comparing floats with ==. 0.1 + 0.2 == 0.3 is false, and it is false in every language with IEEE doubles. Compare with a tolerance, or move the calculation to Rational, BigDecimal, or integers of the smallest unit.
  1. Storing money in floats. A price of 19.99 is not 19.99, and the difference compounds every time you add it to something. Store cents as an Integer, or use BigDecimal when you need decimal rounding rules that an accountant will recognise.
  1. Assuming dup and clone are deep. Both copy one level. A duplicated array shares its elements with the original, so mutating an element through the copy changes what the original sees. Nested data has to be copied deliberately, element by element.
  1. Expecting integer division to produce a fraction. 1 / 3 is 0 and 7 / 2 is 3, because two integers divide into an integer. Use fdiv for a float result or Rational for an exact one, and remember that -7 / 2 is -4 in Ruby because division floors rather than truncates.
  1. Reading a misspelled instance variable and getting nil. @totl has never been assigned, so it evaluates to nil rather than raising, and the failure surfaces later as an arithmetic error on nil. Run with ruby -w, which reports the uninitialised read at the point where it happens.
  1. Relying on a variable created inside a branch that did not run. Ruby creates a local variable when the parser sees the assignment, not when it executes, so a variable assigned only inside an if that was false exists afterwards and holds nil. Code that reads it gets a silent nil rather than a name error, so assign a default before the branch.

Best Practices

  • Freeze the value, not just the name: write .freeze on any constant holding a collection, and freeze the contents too when the collection holds strings or arrays.
  • Put # frozen_string_literal: true at the top of new files, which makes string literals immutable and turns accidental shared mutation into an immediate error.
  • Convert outside data with Integer() and Float(), and reserve to_i and to_f for cases where you have consciously decided that garbage should become zero.
  • Represent money and measurements as integers of the smallest unit, or as Rational or BigDecimal, and let floats handle only quantities where a tiny relative error is genuinely acceptable.
  • Prefer local variables and method arguments over instance state, and treat @@ class variables and $ globals as constructs you can read rather than write.
  • Use equal? when you mean the same object, == when you mean the same value, and remember that eql? is the one hashes use to match keys.
  • Name things by what they hold, in snake_case for variables and methods, CamelCase for classes and modules, and capitals for constants, so the sigil-free names still tell the reader what they are.
  • Run new code once under ruby -w; almost every warning it prints is about a name or a conversion that will bite you later.

Practice Exercises

  1. The Aliasing Lab: Write a script with two strings, a = "shim" and b = a. Print a.equal?(b), then mutate through b with <<, print both, then reassign b and print both again. Now repeat the whole experiment with arrays instead of strings, and finally with integers. Write one sentence explaining why the integer version cannot be made to behave like the other two.
  1. Ten Pence, One Hundred Times: Add 0.1 to a running float total one hundred times and print the result and whether it equals 10.0. Do the same with Rational(1, 10), and again with an integer count of pence converted to pounds only at the end. Report all three answers and state which one you would put in an invoice.
  1. How Deep Is Frozen: Build data = [["a"], ["b"]].freeze and find every mutation you can still perform on it without raising. Then write a small method that returns a genuinely immutable version, freezing each element as well as the outer array, and prove it by attempting the same mutations and rescuing FrozenError.
  1. Harden The Gauge Log: Fix the unit flaw in gauge_log.rb so that only a known set of units is accepted and anything else is reported as a bad row rather than treated as millimetres. Then make the parser survive malformed numbers: collect the failures with their row index, print the good summary and a list of rejected rows, and make sure a single bad line can no longer suppress the entire report.