Introduction to Ruby

Introduction to Ruby in Ruby: In a large machine shop there is a room nobody works in, called the tool crib.

The Analogy: The Tool Crib and Its Check-Out Window

In a large machine shop there is a room nobody works in, called the tool crib. Behind its door are racks of reamers, boring bars, gauge blocks, tap wrenches and micrometers, and in front of its door is a counter with a window in it. A machinist who needs a 3/8 inch reamer does not walk in and take one. They write the tool they want on a paper chit, slide the chit through the window, and wait. The attendant on the other side reads it, walks the racks, and hands something back: the tool, or an equivalent tool, or the chit itself marked "not stocked". In thirty years on the floor a machinist may never learn which shelf anything is actually on.

The arrangement sounds like pointless bureaucracy until you notice what it buys. Because every request goes through the window, the attendant is free to rearrange the racks completely: retire a worn reamer, change supplier, move the entire micrometer drawer to the back wall. No machinist's habit breaks, because the habit was never "reach for the third shelf from the left", it was "ask for a 3/8 reamer". Two shops in two cities can stock entirely different hardware and the same chit works in both, so long as each crib can answer it. And the crib holds everything: the cutting tools obviously, but also the chit pad, the pencil tied to the counter, the ledger the attendant writes in, and the little sign that says CLOSED. There is no category of shop item that gets to bypass the window.

Ruby is that shop, and this is the one idea the entire language is built on. Every value sits behind a window, and every operation is a chit slid through it. When you write 255.to_s(16) you are not passing a dumb number to a global conversion routine, you are handing the integer 255 a chit that reads "render yourself in base sixteen" and letting the integer decide what that means. The rule holds in exactly the places other languages carve out exceptions: nil is an object and answers chits, true is an object, a class is itself an object, and 1 + 2 is the integer 1 receiving a chit named + with the integer 2 clipped to it. Yukihiro Matsumoto, who released Ruby in 1995, said his goal was a language that made programmers happy, and this uniformity is most of the mechanism: there is one rule, and you never have to memorise the list of things it does not apply to.

The failure mode is the chit that comes back rejected. Ask a crib for something it does not stock and the attendant does not improvise, does not hand back an empty box, and does not quietly give you something almost right. They return the chit with the requested tool written on it and the fact that it is not on the racks. In Ruby that is a NoMethodError, and it arrives at the moment the chit is slid through rather than when you first wrote it down, because nothing inspected the chit in advance. The subtler failure is the second shop: two cribs stocking different tools under the same part number. Ruby only ever asks whether the receiver can answer the message, never whether it is the kind of thing you had in mind, so a chit that works against every object in your test shop can be answered wrongly in production by something that merely happens to accept the same name. The flexibility and that whole class of surprise are one property seen from two sides.


Syntax or Core Structure

A Ruby file is a list of expressions, run top to bottom. There is no entry point function you have to declare, no class to wrap free-standing code in, no header, no build step and no semicolons. You save the file and hand it to the interpreter.

# intro.rb

name = "Matz"
year = 1995

puts "Ruby was released in #{year}, by #{name}."

# Every value answers messages, including the values other
# languages treat as primitives or as special cases.
puts 255.to_s(16)
puts "ruby".upcase

temperature = -7
puts temperature.abs

huge = 10 ** 20
puts huge.class
puts 3.14.class
puts nil.class
puts Integer.class

# if is an expression, so it has a value you can assign.
era = if year < 2000
        "twentieth century"
      else
        "twenty first century"
      end
puts era

# A method's value is its last expression. return is optional.
def shout(text)
  text.upcase + "!"
end

puts shout("hello")

Output:

Ruby was released in 1995, by Matz.
ff
RUBY
7
Integer
Float
NilClass
Class
twentieth century
HELLO!

Six details in that file are load bearing. String interpolation with #{} works inside double quoted strings and calls to_s on whatever you put in it, which is why you almost never build strings by concatenation in Ruby. 255.to_s(16) proves the analogy: base conversion is not a library function that takes a number, it is something the number knows how to do. huge holds a twenty one digit value and its class is still Integer, because Ruby switches to arbitrary precision arithmetic silently rather than overflowing. nil.class answers NilClass, so even the absence of a value is a value with a type and methods. Integer.class answers Class, meaning the class itself is an object that sits behind its own window.

The two structural surprises are at the bottom. if is an expression that evaluates to the last thing in the branch it took, so era is assigned directly from it and there is no need for a mutable variable declared above and filled in below. And shout has no return: the value of a method is the value of its final expression. Both facts push Ruby code toward being a sequence of things that produce values rather than a sequence of statements that mutate them.

Running any of this needs one command, and there are four more worth knowing on your first day:

ruby intro.rb            # run the file
ruby -c intro.rb         # parse only, print "Syntax OK", execute nothing
ruby -e 'puts 6 * 7'     # run a single expression
irb                      # interactive shell: one chit at a time
ruby -v                  # which interpreter is actually on your PATH

irb is the one to keep open permanently. Because every value answers questions about itself, the fastest way to learn any Ruby library is to build one of its objects in irb and ask it what it can do. That last command matters more than it looks: most systems ship an old Ruby, and real projects pin a version with a manager such as rbenv, asdf or mise rather than using whatever the operating system provides.


Technical Depth: One Rule, And No Exceptions To It

Most languages have a core of primitive things that behave one way and a layer of user defined things that behave another. Ruby has one layer. The practical payoff is that a single habit of investigation works on everything: build the value, then ask the value about itself.

Everything Answers Messages

ExpressionIts classA message it answersWhat comes back
42Integereven?true
3.9Floatfloor3
"text"Stringlength4
:textSymbolto_sthe string "text"
nilNilClassto_aan empty array
falseFalseClassfrozen?true
(1..5)Rangesum15
[3, 1, 2]Arraysorta new sorted array
5.method(:+)Methodarity1
IntegerClasssuperclassNumeric

That last row is the one worth sitting with. Integer is not a keyword or a compiler concept, it is an object of class Class, stored in a constant, which you can hand chits to at runtime.

samples = [42, 3.9, "text", :text, nil, false, (1..5)]

samples.each do |value|
  puts "#{value.inspect} -> #{value.class}"
end

range = (1..5)
puts range.sum
puts 42.even?
puts 3.9.floor
puts nil.to_a.length

adder = 5.method(:+)
puts adder.arity
puts adder.call(3)

puts Integer.superclass
puts Integer.ancestors.include?(Comparable)

Output:

42 -> Integer
3.9 -> Float
"text" -> String
:text -> Symbol
nil -> NilClass
false -> FalseClass
1..5 -> Range
15
true
3
0
1
8
Numeric
true

5.method(:+) hands you the addition operator as an object you can store in a variable, ask the arity of, and call later. Addition is a method on Integer, spelled with punctuation as a convenience, and nothing more special than that.

The Chit Is Sent, Not Called

Ruby resolves a message when the message is sent, by looking at the object in front of it. No compiler decided in advance that this receiver has this method, which is why the language can ask the question out loud.

values = [42, "42", :forty_two, nil]

values.each do |v|
  puts "#{v.inspect} responds to upcase: #{v.respond_to?(:upcase)}"
end

# The name of the message can be chosen while the program runs.
wanted = :length
puts "abcdef".send(wanted)

# A rejected chit, caught instead of fatal.
begin
  42.upcase
rescue NoMethodError => e
  puts "rejected: #{e.class}"
end

Output:

42 responds to upcase: false
"42" responds to upcase: true
:forty_two responds to upcase: true
nil responds to upcase: false
6
rejected: NoMethodError

This is the mechanism behind duck typing. A method that formats a report does not need to be told it was handed an invoice; it needs the object to answer each and total. Any object that answers those is acceptable, including a test double that exists only in a spec file. Prefer public_send over send when the message name comes from outside your code, because plain send will happily invoke a private method and quietly defeat the boundary the author drew.

puts, print And p Do Three Different Jobs

Choosing the wrong one of these is the most common reason a beginner's output does not look like the tutorial's.

MethodHow it renders the valueNewlineWhat it returns
putsto_s, and one line per element for an arrayadds one unless the text already ends with onenil
printto_snevernil
pinspect, so strings keep their quotesalwaysthe value you passed in
ppinspect with line breaks for nested structuresalwaysthe value you passed in
value = "text"

puts "-- puts unwraps an array --"
puts ["alpha", "beta"]

puts "-- print adds nothing at all --"
print "one"
print "two"
print "\n"

puts "-- p renders the object as source, and returns it --"
returned = p value
puts returned.equal?(value)

puts "-- while puts returns nil --"
result = puts "printed"
puts result.inspect

Output:

-- puts unwraps an array --
alpha
beta
-- print adds nothing at all --
onetwo
-- p renders the object as source, and returns it --
"text"
true
-- while puts returns nil --
printed
nil

Because p returns its argument, you can drop it into the middle of an expression to inspect a value without restructuring anything, which makes it the workhorse of Ruby debugging. puts nil prints an empty line rather than the word nil, so a blank line in your output is usually a nil you did not expect, and swapping that puts for a p will show it to you.

Symbols Are Names, Strings Are Text

Newcomers read :admin as a string with odd punctuation. It is a different kind of thing: a name, interned once for the life of the process.

PropertyStringSymbol
Written as"admin":admin
Mutableyes, unless frozennever
Two identical literalstwo separate objectsone and the same object
Comparison costwalks the charactersa single identity check
Natural usetext you will slice, build or show a usera name: a hash key, a method name, a state
Reclaimed by the collectoryesyes for dynamically created ones, since Ruby 2.2
a = "admin"
b = "admin"
puts a == b
puts a.equal?(b)

x = :admin
y = :admin
puts x == y
puts x.equal?(y)

puts a.frozen?
puts x.frozen?

role = { name: "Ada", level: :admin }
puts role[:name]
puts role.keys.inspect
puts role[:level].to_s.upcase

Output:

true
false
true
true
false
true
Ada
[:name, :level]
ADMIN

Two string literals with the same characters are equal in value and are not the same object, so each one costs an allocation. Two identical symbols are the same object, which is why symbols are the default choice for hash keys and why { name: "Ada" } is shorthand for a hash whose key is the symbol :name.

The Tools You Will Actually Type

CommandJob
ruby file.rbrun a script
ruby -c file.rbparse and report syntax only, execute nothing
ruby -w file.rbrun with warnings enabled, which you should do while learning
irbinteractive shell, the fastest way to interrogate any object
gem install rubocopinstall a library or tool from RubyGems
bundle installinstall the exact versions a Gemfile pins
bundle exec rspecrun a tool under the project's pinned versions rather than the system's
rake -Tlist the tasks a Rakefile defines
rubocopreport style and correctness issues, with autocorrection available
ruby -vprint the interpreter version actually being used

The habit worth forming immediately is bundle exec. Without it you run whatever version of a tool happens to be installed globally, and the first symptom is a test suite that passes on your machine and fails on everyone else's.


Real World Example: A Shift Report From The Crib Ledger

The crib attendant writes one line per movement: time, whether the tool went out or came back, which tool, and who. At the end of a shift the supervisor wants three things from that ledger: how much traffic each tool saw, what is still out, and who was busiest. This is about forty lines of Ruby with no dependencies.

# crib_report.rb -- summarise one shift of tool crib traffic.

LEDGER = <<~ENTRIES
  0705 ISSUE  reamer-3-8   hallam
  0712 ISSUE  mic-0-1      okafor
  0728 ISSUE  endmill-6mm  hallam
  0801 RETURN reamer-3-8   hallam
  0815 ISSUE  reamer-3-8   deng
  0822 ISSUE  gauge-block  okafor
  0840 RETURN endmill-6mm  hallam
  0905 ISSUE  mic-0-1      deng
  0910 RETURN mic-0-1      okafor
  0930 ISSUE  reamer-3-8   okafor
ENTRIES

Entry = Struct.new(:minute, :action, :tool, :who)

def parse(text)
  text.lines.map do |line|
    stamp, action, tool, who = line.split
    Entry.new(stamp[0, 2].to_i * 60 + stamp[2, 2].to_i, action, tool, who)
  end
end

def issues_per_tool(entries)
  counts = Hash.new(0)
  entries.each { |e| counts[e.tool] += 1 if e.action == "ISSUE" }
  counts
end

def still_out(entries)
  open = Hash.new(0)
  entries.each do |e|
    open[e.tool] += 1 if e.action == "ISSUE"
    open[e.tool] -= 1 if e.action == "RETURN"
  end
  open.reject { |_tool, n| n.zero? }
end

entries = parse(LEDGER)

issues  = entries.count { |e| e.action == "ISSUE" }
returns = entries.count { |e| e.action == "RETURN" }

puts "entries read: #{entries.size}"
puts "issues: #{issues}  returns: #{returns}"

first = entries.first
last  = entries.last
puts "first: minute #{first.minute} #{first.action} #{first.tool} by #{first.who}"
puts "last:  minute #{last.minute} #{last.action} #{last.tool} by #{last.who}"

puts
puts "issues per tool"
issues_per_tool(entries).sort_by { |tool, n| [-n, tool] }.each do |tool, n|
  puts "  #{tool.ljust(12)}#{n}"
end

puts
puts "still out at shift end"
still_out(entries).sort.each do |tool, n|
  puts "  #{tool.ljust(12)}#{n} out"
end

busiest = entries.group_by(&:who).max_by { |who, list| [list.size, who] }
puts
puts "busiest machinist: #{busiest.first} with #{busiest.last.size} movements"

Output:

entries read: 10
issues: 7  returns: 3
first: minute 425 ISSUE reamer-3-8 by hallam
last:  minute 570 ISSUE reamer-3-8 by okafor

issues per tool
  reamer-3-8  3
  mic-0-1     2
  endmill-6mm 1
  gauge-block 1

still out at shift end
  gauge-block 1 out
  mic-0-1     1 out
  reamer-3-8  2 out

busiest machinist: okafor with 4 movements

The first thing worth noticing is how little scaffolding there is. Struct.new produces a real class with four reader methods in one line, so e.tool is a method call on an object rather than a lookup into an untyped hash. stamp, action, tool, who = line.split destructures the four fields of a line in one assignment. Hash.new(0) builds a hash whose default value is zero, which is what makes counts[e.tool] += 1 legal on a key that has never been seen. None of these are library extras; they are the standard library doing the boring work.

The second is that every summary is a chain of messages, each returning a new object for the next one to receive. issues_per_tool hands back a hash; the hash answers sort_by, which hands back an array of pairs; the array answers each. The sort key [-n, tool] deserves attention because it is doing two jobs: the negated count sorts descending, and the tool name breaks ties alphabetically. Without that second element, two tools with one issue each could come out in either order, and a report that changes between runs on identical input is a report nobody can diff.

The third is the deliberate absence of loops with counters. There is no index variable anywhere, and no place where the code walks off the end of a collection, because map, each, count, group_by and max_by all take the walking as their own responsibility. group_by(&:who) builds a hash from each distinct machinist to their entries, and &:who is shorthand for the block that sends who to each element. That single line replaces about eight lines of manual bucketing.

Now the honest limits. still_out has a genuine bug, not a rough edge: it counts issues minus returns and then drops only the tools whose count is exactly zero, so a tool borrowed on the previous shift and handed back on this one lands at minus one and gets printed as "-1 out". The report presents nonsense as a finding, and if that number were ever fed into a stock figure it would silently reduce it. The correct rule is to drop anything at or below zero and log the negatives separately as unmatched returns, because they are a real event the ledger is telling you about. Beyond that: parse trusts split, so a tool name containing a space shifts every field right and lands nil in who with no complaint; nothing checks that a line had four fields or that the timestamp was digits, since "oops"[0, 2].to_i is a cheerful zero; the busiest machinist is a genuine tie between hallam and okafor at four movements each, resolved by name order, so the program states a preference as though it were a result; and the ledger is a constant inside the file, which means the program cannot yet read the actual log it exists to summarise.


Common Mistakes

  1. Looking for a free function when the object has the method. Newcomers write length(name) or reach for a String utility module. In Ruby the value owns the operation: name.length, name.reverse, 255.to_s(16). If you find yourself wanting a helper that takes one argument and inspects it, check whether that argument's class already answers the question.
  1. Assuming zero and the empty string are falsy. Only false and nil are false in a condition. 0, "" and [] are all true, so if count is true even when count is zero. Test the thing you actually mean, such as count.zero? or list.empty?.
  1. Using puts when you meant p. puts renders through to_s, which strips the quotes from a string and prints an empty line for nil. When you are debugging you want p, which renders through inspect and shows you the difference between the string "5" and the integer 5.
  1. Chaining off puts. puts returns nil, so puts(value).upcase fails and x = puts "hi" leaves x as nil. p returns its argument, which is why it can be dropped into the middle of an expression and puts cannot.
  1. Mixing string keys and symbol keys in the same hash. { "id" => 1 } and { id: 1 } are different hashes with different keys, and hash[:id] returns nil for the first one. Pick one convention per data structure and convert at the boundary where external data arrives.
  1. Expecting a misspelled method name to be caught before the line runs. Nothing checks your chits in advance. A typo inside a rarely taken branch waits there until that branch runs, which is the strongest argument for tests in a dynamic language and the reason RuboCop and a good editor are worth configuring on day one.
  1. Trusting the return value of a bang method. Several mutating methods return nil when they had nothing to change: list.uniq! gives back nil if the array already had no duplicates. Writing result = list.uniq! therefore works on your test data and returns nil in production. Mutate on one line and use the variable on the next.
  1. Installing gems globally and skipping Bundler. gem install rails puts one version on your machine; a project needs a specific set that works together. Declare them in a Gemfile, commit the Gemfile.lock, and run project tools through bundle exec so your machine and your build server agree.
  1. Learning from tutorials written for a much older Ruby. Advice involving require "rubygems", FixNum, or hashes written only with => predates changes that are now a decade old. Check ruby -v, prefer documentation that states its version, and be suspicious of any Ruby example that has no Gemfile in sight.

Best Practices

  • Keep an irb session open while you work, and answer questions about a library by building one of its objects and interrogating it rather than by searching for prose about it.
  • Run scripts with ruby -w while you are learning; the warnings it prints are almost always about something you genuinely did not intend.
  • Use symbols for names and strings for text: symbols for hash keys, states and method names, strings for anything a user will read or you will slice.
  • Reach for string interpolation rather than concatenation, since "total: #{n}" calls to_s for you and "total: " + n raises when n is not already a string.
  • Let expressions produce values. Assign from an if or a case instead of declaring a variable above and filling it in below, and let a method's last expression be its return value.
  • Pin your interpreter with rbenv, asdf or mise, commit the version file, and never rely on the Ruby the operating system happens to ship.
  • Run every project tool through bundle exec so the versions in your Gemfile.lock are the versions that actually execute.
  • Add RuboCop early and accept its defaults. Ruby has an unusually settled community style, and adopting it removes an entire category of review argument for free.

Practice Exercises

  1. Interrogate Ten Values: In irb, take these ten values: 42, -3.5, "ruby", :ruby, nil, true, (1..3), [1, 2], a hash with one pair, and String itself. For each one print its class, its frozen? answer, and how many methods it answers via methods.size. Then write one sentence explaining why String.class is not String.
  1. Force And Then Catch A Rejected Chit: Write a script that calls .upcase on nil and let it crash. Copy the exact error message down, including which class it names. Now wrap the call in begin and rescue NoMethodError, print the class of the error, and finally rewrite the code so it never raises at all by guarding with respond_to?. Explain in a comment which of the three versions you would want in production and why.
  1. Prove The Symbol Claim: Write a script that creates two identical string literals and two identical symbols, then prints four lines: whether each pair is ==, and whether each pair is equal?. Add a fifth line printing whether "admin".to_sym.equal?(:admin). Predict all five results before you run it, then explain any you got wrong in terms of allocation.
  1. Fix The Crib Report: Take crib_report.rb and repair the negative count bug: unmatched returns should be reported under their own heading rather than appearing as a tool that is minus one out. Then add a section listing who currently holds which tool, which requires tracking the person on each ISSUE and clearing them on the matching RETURN. Finally make the busiest machinist line honest when there is a tie, naming every person at the top count rather than picking one.