Ruby/Reflection/singleton method added

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

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

Add method to an instance

a = "hello" 
b = a.dup 
def a.to_s 
    "The value is "#{self}"" 
end 
def a.twoTimes 
    self + self 
end 
a.to_s 
a.twoTimes
b.to_s



"class

a = "hello" 
b = a.dup 
class <<a 
    def to_s 
    "The value is "#{self}"" 
    end 
    def twoTimes 
    self + self 
    end 
end 
a.to_s 
a.twoTimes
b.to_s



Use singleton_method_added to call a singleton method

class MyClass
  def MyClass.singleton_method_added(sym)
    puts "Added method #{sym.id2name} to class MyClass."
  end
  def MyClass.meth1
    puts "I"m meth1."
  end
end
def MyClass.meth2
  puts "And I"m meth2."
end