在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"].
# 完成添加。