Dynamic Dispatch
- There is another way to call a method in Ruby - using the
send
method - First parameter is the method name/symbol; the rest (if any) are method arguments
1 | class Dog |
Dynamic Method
- Not only can you call methods dynamically (with send), you can also define methods dynamically
define_method :method_name
and ablock
which contains the method definition
1 | class Whatever |
1 | require_relative 'store' |
Ghost Methods
- method_missing gives you the power to “fake” the methods
- Called “ghost methods” because the methods don’t really exist
1 | class Mystery |
Struct and OpenStruct
Struct
: Generator of specific classes, each one of which is defined to hold a set of variables and their accessors (“Dynamic Methods”)OpenStruct
: Object (similar to Struct) whose attributes are created dynamically when first assigned (“Ghost methods”)
1 | Customer = Struct.new(:name, :address) do # block is optional |