Metaprogramming
Send messages
Every method call is a message, and send delivers a message chosen at runtime.
Pass the method name as a symbol or a string, and prefer public_send when private methods must stay off limits.
name = "ada" puts name.send(:upcase) puts name.public_send("upcase")
ruby send_demo.rb
ADA
ADA
define_method
The define_method call creates methods inside a loop, so similar methods need no repetition.
Each generated method closes over its own word, so hello and bye remember different values.
class Greeter ["hello", "bye"].each do |word| define_method(word) do puts word.upcase end end end Greeter.new.hello
ruby greeter_demo.rb
HELLO
method_missing
When no method matches, Ruby calls method_missing instead of failing right away.
Read the value from the hash when the key exists, call super otherwise, and mirror the logic in respond_to_missing?
class Config def initialize(values) @values = values end def method_missing(name, *args) return @values[name] if @values.key?(name) super end def respond_to_missing?(name, include_private = false) @values.key?(name) || super end end config = Config.new({ theme: "dark" }) puts config.theme
ruby config_demo.rb
dark
Freeze shared state
Shared constants invite accidental changes, and freeze locks an object against mutation.
A frozen hash raises FrozenError on write, while frozen? reports the locked state.
SETTINGS = { theme: "dark", retries: 3 }.freeze puts SETTINGS.frozen?
ruby freeze_demo.rb
true
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does this program print?
name = "ada" puts name.send(:capitalize)Answer
Ada
send delivers the message the symbol names, and capitalize upcases the first letter.
-
What does this program print?
class Greeter ["hello", "bye"].each do |word| define_method(word) do word.upcase end end end puts Greeter.new.byeAnswer
BYE
Each generated method closes over its own word, so bye upcases bye.
-
What does this program print?
class Config def initialize(values) @values = values end def method_missing(name, *args) return @values[name] if @values.key?(name) super end end puts Config.new({ theme: "dark" }).themeAnswer
dark
The missing method reads the hash, and the key is there, so puts prints its value.
-
What does this program print?
class Config def initialize(values) @values = values end def method_missing(name, *args) return @values[name] if @values.key?(name) super end end begin Config.new({}).theme rescue NoMethodError => e puts e.class endAnswer
NoMethodError
super passes the call to the parent, which raises NoMethodError when the key is absent.
-
What does this program print?
settings = { theme: "dark" }.freeze begin settings[:theme] = "light" rescue FrozenError => e puts e.class endAnswer
FrozenError
A frozen hash refuses the write, and the frozen state is what the object reports.
-
Why prefer
public_sendoversendfor a name that comes from outside?Answer
public_send refuses private methods, so outside input cannot reach them
The caller should not be able to name a private method, and public_send enforces the visibility.
-
What does
superdo insidemethod_missing?Answer
Calls the parent implementation, which raises the usual error
The call keeps an unknown name an error instead of turning every typo into a silent nil.
-
Why does the class also define
respond_to_missing??Answer
To make respond_to? answer for the names method_missing handles
Code that asks respond_to? before calling needs the same answer as the call itself.
-
What does
define_methodlet a class do thatdefdoes not?Answer
Create a method whose name is computed at runtime
The loop in the example builds hello and bye from data rather than from source text.
-
Why freeze a shared constant such as a settings hash?
Answer
It prevents an accidental write to state that every caller shares
A shared constant is easy to change by accident, and freeze turns that into a loud FrozenError.
Article author: Arthur Isaev