def là keyword — tên method phải là identifier tĩnh biết lúc viết code. define_method là method nhận tên động (string/symbol), cho phép tạo method theo pattern lúc runtime.
class Status
STATES = %i[pending active suspended]
STATES.each do |state|
define_method("#{state}?") do
@state == state
end
define_method("#{state}!") do
@state = state
end
end
end
obj = Status.new
obj.active! # setter
obj.active? # => true
obj.pending? # => falseKhi dùng define_method:
- Sinh nhiều method theo pattern (tránh copy-paste).
- Tên method đến từ data (symbol array, config...).
- Cần closure (capture biến từ scope tạo method).
define_method + block là closure, còn def thì không capture biến ngoài.
def is a keyword — the method name must be a static identifier known at write-time. define_method is a method that accepts a dynamic name (string/symbol), enabling method creation from patterns at runtime.
class Status
STATES = %i[pending active suspended]
STATES.each do |state|
define_method("#{state}?") do
@state == state
end
define_method("#{state}!") do
@state = state
end
end
end
obj = Status.new
obj.active!
obj.active? # => true
obj.pending? # => falseWhen to use define_method:
- Generate many methods from a pattern (no copy-paste).
- Method names come from data (symbol array, config).
- Need a closure (capture variables from the outer scope).
Key distinction: a define_method block is a closure and captures outer variables; a def body is not.