Ref. WGR Chapter 4, Modules and program organization
module Food
FRUITS = ["Apple", "Banana", "Cherry"]
end
From outside the module:
Food::FRUITS.each do |fruit|
puts "This #{fruit} is yummy!"
end
module Speakers
class Hello
def say_hello
puts "hi"
end
end
end
From outside the module:
x = Speakers::Hello.new
x.say_hello
module Greetings
def greet
puts "Hello!"
end
end
class Person
include Greetings
end
alice = Person.new
alice.greet
Greeter.new #=> undefined method `new' for Greeter:Module
module Stacky
def stack
@stack ||= []
end
def push obj
stack.push obj
end
def pop
stack.pop
end
end
@stack
will become an instance variable on the includer
load
vs. require
vs. include
vs. extend
load 'config.rb'
load
ed more than once, last one sticksrequire 'config'
require
ing the same file more than once has no effect, first one sticksinclude Config
self
, usually to add class methods
extend Config
<
inherits a superclass (pronounced "inherits from", not "extends")
class BetterString < String
class Foo
include A
include B
include A #<< ignored!
end
prepend
method for even more fun!whiz.rb
:module Whiz
VERSION = "1.0.2"
class GeeGaw
# ...
end
end
whiz/bang.rb
:module Whiz
class Bang
def geegaw
# inside the module, its members are in scope
@geegaw ||= GeeGaw.new
end
end
end
client.rb
:require "whiz"
require "whiz/bang"
puts Whiz::VERSION bang = Whiz::Bang.new ```
/