方法定义是表达式

在 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.