Inheritance and Modules
Constants and Namespaces
Modules can group constants and classes under a qualified name.
namespace
A module name can act as a namespace for constants and classes that belong together.
Constants and Namespaces
constants_namespaces.rb
Replay: real traced execution (multi-file project)
module Store
TAX_PERCENT = 8
class Calculator
def self.total(subtotal)
subtotal + subtotal * TAX_PERCENT / 100
end
end
end
subtotal = 25
total = Store::Calculator.total(subtotal)
puts "tax_percent=#{Store::TAX_PERCENT}"
puts "subtotal=#{subtotal}"
puts "total=#{total}"
module Store
TAX_PERCENT = 8
class Calculator
def self.total(subtotal)
subtotal + subtotal * TAX_PERCENT / 100
end
end
end
subtotal = 10
total = Store::Calculator.total(subtotal)
puts "tax_percent=#{Store::TAX_PERCENT}"
puts "subtotal=#{subtotal}"
puts "total=#{total}"
module Store
TAX_PERCENT = 8
class Calculator
def self.total(subtotal)
subtotal + subtotal * TAX_PERCENT / 100
end
end
end
subtotal = 40
total = Store::Calculator.total(subtotal)
puts "tax_percent=#{Store::TAX_PERCENT}"
puts "subtotal=#{subtotal}"
puts "total=#{total}"
TAX_PERCENT ← 8, subtotal ← 25
1module Store2 TAX_PERCENT→ 8 = 834 class Calculator5 def self.total(subtotal)6 subtotal + subtotal * TAX_PERCENT / 1007 end8 end9end1011subtotal→ 25 = 25 #@subtotal=10, 4012total = Store::Calculator.total(subtotal)27def self.total(subtotal)
4class Calculator5 def self.total(subtotal25)6 subtotal25 + subtotal * TAX_PERCENT8 / 1007 endtotal ← 27
11subtotal = 25 #@subtotal=10, 4012total→ 27 = Store::Calculator.total(subtotal)271314puts "tax_percent=#{Store::TAX_PERCENT8}"15puts "subtotal=#{subtotal25}"16puts "total=#{total27}"outputtax_percent=8 subtotal=25 total=27
TAX_PERCENT ← 8, subtotal ← 10
1module Store2 TAX_PERCENT→ 8 = 834 class Calculator5 def self.total(subtotal)6 subtotal + subtotal * TAX_PERCENT / 1007 end8 end9end1011subtotal→ 10 = 1012total = Store::Calculator.total(subtotal)10def self.total(subtotal)
4class Calculator5 def self.total(subtotal10)6 subtotal10 + subtotal * TAX_PERCENT8 / 1007 endtotal ← 10
11subtotal = 1012total→ 10 = Store::Calculator.total(subtotal)101314puts "tax_percent=#{Store::TAX_PERCENT8}"15puts "subtotal=#{subtotal10}"16puts "total=#{total10}"outputtax_percent=8 subtotal=10 total=10
TAX_PERCENT ← 8, subtotal ← 40
1module Store2 TAX_PERCENT→ 8 = 834 class Calculator5 def self.total(subtotal)6 subtotal + subtotal * TAX_PERCENT / 1007 end8 end9end1011subtotal→ 40 = 4012total = Store::Calculator.total(subtotal)43def self.total(subtotal)
4class Calculator5 def self.total(subtotal40)6 subtotal40 + subtotal * TAX_PERCENT8 / 1007 endtotal ← 43
11subtotal = 4012total→ 43 = Store::Calculator.total(subtotal)431314puts "tax_percent=#{Store::TAX_PERCENT8}"15puts "subtotal=#{subtotal40}"16puts "total=#{total43}"outputtax_percent=8 subtotal=40 total=43