Ruby/Reflection/module eval
Материал из Wiki.crossplatform.ru
Add a new method with module_eval
class String module_eval %{def last(n) self[-n, n] end} end p "Here"s a string.".last(7) # => "string." String.module_eval %{def last(n) self[-n, n] end} p "Here"s a string.".last(7) # => "string."
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