Add a new method with module_eval : module_eval « Reflection « Ruby






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

 








Related examples in the same category

1.Use module_eval to create dynamic method