January 2019
Intermediate to advanced
246 pages
5h 23m
English
The self. prefix for top-level methods can become a bit cumbersome. You can get rid of it by making a module extend itself:
| | module Moral |
| | extend self |
| | VERY_BAD = 0 |
| | BAD = 1 |
| | |
| | def sin(badness) |
| | puts "Assessing the sin of #{badness}" |
| | end |
| | end |
You’ll see this common idiom in modules—for example, module Math uses it in its code. When applied, a module is used as a namespace and you can write Module.method, like Math.sin. Now if this looks like a class method to you, it is! Remember: A module is of type Class.
| | require "./moral2" |
| | |
| | y = Math.sin(Math::PI/4) # => 0.70710678118654746 |
| | wrongdoing = Moral.sin(Moral::VERY_BAD) ... |
Read now
Unlock full access