首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

新旧两种模式定义singleton method

2012-12-20 
新旧两种方式定义singleton methodclass Aclass selfdef class_nameto_sendendendA.define_singleton_m

新旧两种方式定义singleton method

class A  class << self    def class_name      to_s    end  endendA.define_singleton_method(:who_am_i) do  "I am: #{class_name}"endA.who_am_i   # ==> "I am: A"guy = "Bob"guy.define_singleton_method(:hello) { "#{self}: Hello there!" }guy.hello    #=>  "Bob: Hello there!"



class Fred  def initialize(p1, p2)    @a, @b = p1, p2  endendfred = Fred.new('cat', 99)fred.instance_variable_get(:@a)    #=> "cat"fred.instance_variable_get("@b")   #=> 99class Fred  def initialize(p1, p2)    @a, @b = p1, p2  endendfred = Fred.new('cat', 99)fred.instance_variable_set(:@a, 'dog')   #=> "dog"fred.instance_variable_set(:@c, 'cat')   #=> "cat"fred.inspect                             #=> "#<Fred:0x401b3da8 @a="dog", @b=99, @c="cat">"class Dummy  attr_reader :var  def initialize    @var = 99  end  def remove    remove_instance_variable(:@var)  endendd = Dummy.newd.var      #=> 99d.remove   #=> 99d.var      #=> nilclass B  def self.run(method)    singleton_class = class << self; self; end    singleton_class.send(:define_method, method) do        puts "Method #{method}"    end  endend



[:failure, :error, :success].each do |method| define_method method do    self.state = method endend#Dynamically defining methods in a loop creates a more concise definition, but it's not a particularly readable one. To address this issue I define the def_each method. The motivation for defining a def_each method is that it is easy to notice and understand while scanning a source file.class Class def def_each(*method_names, &block)   method_names.each do |method_name|     define_method method_name do        instance_exec method_name, &block     end   end endend

热点排行