Use module_eval to create dynamic method : module_eval « Reflection « Ruby






Use module_eval to create dynamic method


class Numeric
  [['add', '+'], ['subtract', '-'],
   ['multiply', '*',], ['divide', '/']].each do |method, operator|
    module_eval %{ def #{method}_2
                     self #{operator} 2
                   end }
  end
end

4.add_2                                                  # => 6
10.divide_2                                              # => 5

 








Related examples in the same category

1.Add a new method with module_eval