Ruby Namespaces
A module can wrap classes and constants under one name. The wrapped names stay separate from names outside the module.
A class inside a module
Book sits inside Store. The full name Store::Book builds a book object.
module Store
class Book
def initialize(title)
@title = title
end
def show
puts @title
end
end
end
book = Store::Book.new("Dune")
book.showSame name, two namespaces
Kitchen and Garage each hold a Tool class. The full name in each line picks which Tool gets built.
module Kitchen
class Tool
def use
puts "Cooks the meal"
end
end
end
module Garage
class Tool
def use
puts "Fixes the car"
end
end
end
kitchen_tool = Kitchen::Tool.new
garage_tool = Garage::Tool.new
kitchen_tool.use
garage_tool.useA constant inside a namespace
OPEN_HOUR lives inside Store. The nested Sign class reads it directly, and the last line reaches it with the full name.
module Store
OPEN_HOUR = 9
class Sign
def show
puts "Opens at #{OPEN_HOUR}"
end
end
end
sign = Store::Sign.new
sign.show
puts Store::OPEN_HOURExample
module Store
SECTION = "Fiction"
class Book
def initialize(title)
@title = title
end
def show
puts "#{@title} sits in #{SECTION}"
end
end
end
module Archive
class Book
def show
puts "Archived book"
end
end
end
store_book = Store::Book.new("Dune")
store_book.show
archive_book = Archive::Book.new
archive_book.show
puts Store::SECTIONKey points
- A class defined inside a module lives under the module name.
- The :: shape joins the module name to the wrapped name.
- Two modules can hold classes with the same name.
- The full name picks the class that a line builds.
- Constants can live inside a namespace too.
- A nested class can read the constants of its module directly.
In this example, Store wraps a Book class and a SECTION constant. Store::Book builds the store book, and its show method reads SECTION directly. Archive holds its own Book, and Archive::Book builds that separate class.
Note
Namespaces keep big programs tidy when names would clash.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How does a program build an object of the Book class inside Store?