Who may call what
A class has an inside and an outside. Methods are public unless you say otherwise: whoever holds the object may call them. A private method is the class's own business – a helper like as_hours in lesson 108, which you want to be free to change without breaking anyone. Ruby enforces it simply: a private method can only be called from inside the object, without an object in front – or with self. in front, allowed since Ruby 2.7.
Two ways to write it: a bare private line makes every method below it private; private def … marks just one. That works because def returns the method's name as a symbol, and private takes symbols – so private attr_reader :rate works too.
class Invoice
def initialize(minutes, rate)
@minutes = minutes
@rate = rate
end
def total = (self.hours * rate).round(2)
private def hours = @minutes / 60.0
private attr_reader :rate
end
bill = Invoice.new(90, 120)
begin
bill.hours
rescue NoMethodError => e
puts e.message
end
bill.totaltotal may use hours and rate; from the outside you get a NoMethodError that says why. Between the two sits protected: such a method may be called with an object in front, but only from inside methods of the same class (or a subclass). That's what you need to compare two objects by something that is nobody else's business. The classic is <=> for Comparable (lesson 113):
class Lap
include Comparable
attr_reader :runner
def initialize(runner, seconds)
@runner = runner
@seconds = seconds
end
def <=>(other) = seconds <=> other.seconds
protected
attr_reader :seconds
end
fox = Lap.new("Fox", 42)
cat = Lap.new("Cat", 57)
[fox < cat, [cat, fox].min.runner, (fox.seconds rescue "no access")]Inside <=>, other.seconds works; out here, fox.seconds doesn't. Constants can be private too: private_constant keeps Vault::PIN out of reach, while the class's own methods still use PIN. And all of this states an intention – it is not a lock. send calls private methods as well: useful in a test, a smell in ordinary code. public_send respects visibility. When a method name comes from outside – a parameter, a config file, a form – call it with public_send:
class Vault
PIN = 1234
private_constant :PIN
def self.open?(guess) = guess == PIN
private def contents = "bacon"
end
safe = Vault.new
{
open: Vault.open?(1234),
constant: (Vault::PIN rescue $!.message),
send: safe.send(:contents),
public_send: (safe.public_send(:contents) rescue $!.message)
}Monkey patching
Ruby's classes are open: anyone may reopen Integer or String and add a method. That's called a monkey patch, and timelog is tempted – 1.5.hours reads so nicely. But the change is global: every line of every gem in the program sees it, and when two libraries have the same idea in different ways, the one loaded last wins. Silently:
# a library loaded first: half of 7 minutes is 3
class Integer
def half = self / 2
end
# another library, loaded later, has its own idea
class Integer
def half = self / 2.0
end
# the first library's code now gets 3.5
puts 7.half
# the method sits in Integer itself: everyone sees it
puts Integer.instance_method(:half).owner
# tidy up: all lessons on this page share one Ruby
Integer.remove_method(:half)That's not a made-up danger: Rails' ActiveSupport puts hours, minutes and many more on every number – welcome in a Rails app, a surprise for a gem that brought its own hours. (That's why our exercise says hrs.)
Refinements
The scoped fix is a refinement. Inside a module, refine String do … end collects the changes; using switches them on – but only for the code written after it, in the same file or class body. Everyone else keeps the plain String:
module ClockStrings
refine String do
def to_minutes
hours, minutes = split(":").map(&:to_i)
hours * 60 + minutes
end
end
end
class Timecard
using ClockStrings # from here to this class's end
def self.total(*times) = times.sum(&:to_minutes)
end
{
inside: Timecard.total("1:30", "0:45"),
outside: ("1:30".to_minutes rescue $!.class),
global: String.method_defined?(:to_minutes)
}Inside Timecard a string knows to_minutes; one line below the class it doesn't, and String itself never changed. That's what lexical scope means: what counts is where code is written, not who calls it. Timecard.total works from anywhere, because its method was written inside the scope.
usingmay stand at the top level of a file (it holds to the end of the file) or in a class or module body (to itsend) – never inside a method: there it raises aRuntimeError.- Calls by name see the refinement inside its scope too:
send,public_send,&:to_minutes, evenrespond_to?(checked on Ruby 4.0). String.method_defined?,instance_methodsand"1:30".methodslook at the class itself and never list a refined method – a handy test that nothing leaked.
using near the top – the gem never changes your strings behind your back. In this page each cell runs through eval with the lesson's binding: a top-level using in a cell stays on for this lesson's later cells, but no other lesson sees it.Integer. In TimeUnits, refine Numeric (that covers Integer and Float at once) with hrs, which turns hours into whole minutes (1.5.hrs → 90), and mins (45.mins → 45), and switch it on with using TimeUnits. In Stint, write longer_than?(other) and make minutes a protected reader. The check also makes sure that hrs and mins are not on Integer or Float for everyone. (If you try a monkey patch first, Numeric.remove_method(:hrs) takes it back.)module TimeUnits
# refine Numeric do
# def hrs = ... # 1.5.hrs => 90 (minutes)
# def mins = ... # 45.mins => 45
# end
end
# using TimeUnits
class Stint
attr_reader :task
def initialize(task, minutes)
@task = task
@minutes = minutes
end
# def longer_than?(other)
# ... # compare minutes with other.minutes
# end
# protected: other stints may read minutes, nobody else
end
# review = Stint.new("Code review", 1.5.hrs)
# standup = Stint.new("Standup", 20.mins)
# [review.longer_than?(standup), Integer.method_defined?(:hrs)]