Defining a method in Ruby 2.x returns a symbol representing the name:
class Example
puts def hello
end
end
#=> :hello
This allows for interesting metaprogramming techniques. For instance, methods can be wrapped by other methods:
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.