方法定義是表示式
在 Ruby 2.x 中定義方法會返回表示名稱的符號:
class Example
puts def hello
end
end
#=> :hello
這允許有趣的超程式設計技術。例如,方法可以通過其他方法包裝:
class Class
def logged(name)
original_method = instance_method(name)
define_method(name) do |*args|
puts "Calling #{name} with #{args.inspect}."
original_method.bind(self).call(*args)
puts "Completed #{name}."
end
end
end
class Meal
def initialize
@food = []
end
logged def add(item)
@food << item
end
end
meal = Meal.new
meal.add "Coffee"
# Calling add with ["Coffee"].
# Completed add.