Ruby/Method/define method

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Add a new method with define_method

class String
  define_method("last") do |n|
   self[-n, n]
  end
end
p "Here"s a string.".last(7)               # => "string."



define_method method allows you to create methods on the fly.

#!/usr/bin/env ruby
class Meta
  %w{ j e m k l }.each do |n|
    define_method(n) { puts "My name is #{n.capitalize} Bennet." }
  end
end
Meta.instance_methods - Object.instance_methods 
meta = Meta.new
meta.e



Metaprogramming with String Evaluations

class Numeric
 [["add", "+"], ["subtract", "-"],
  ["multiply", "*",], ["divide", "/"]].each do |method, operator|
    define_method("#{method}_2") do
      method(operator).call(2)
    end
  end
end