Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby-在Ruby类的元类中定义自己的方法_Ruby_Metaprogramming_Metaclass_Class Method - Fatal编程技术网

Ruby-在Ruby类的元类中定义自己的方法

Ruby-在Ruby类的元类中定义自己的方法,ruby,metaprogramming,metaclass,class-method,Ruby,Metaprogramming,Metaclass,Class Method,方法m3会发生什么情况,如何访问m3方法,以及它将在类或元类中定义在哪里?但是,如果我尝试使用.m3或对象类方法访问它,它就不存在 Ruby中的每个对象都有一个隐藏的单例类,位于其自身和其父类之间 class A @@class_var = "A class variable" def initialize @var = "A instance variable" end def m1 puts @var end def m2 puts @@cla

方法m3会发生什么情况,如何访问m3方法,以及它将在类或元类中定义在哪里?但是,如果我尝试使用.m3或对象类方法访问它,它就不存在

Ruby中的每个对象都有一个隐藏的单例类,位于其自身和其父类之间

class A
  @@class_var = "A class variable"
  def initialize
    @var = "A instance variable"
  end
  def m1
    puts @var
  end
  def m2
    puts @@class_var
  end
end

class << A
  def self.m3
    puts "im m3"
  end
end
singleton类很有用,因为它允许您定义只应用于单个对象的方法和


你可以打开一个对象的singleton类对其进行更改,这个类的简短答案是delete self。这有点像问我写了这段代码,但我不知道它是做什么的,你呢?:-你想完成什么?这个问题与元编程无关
class A; end
a = A.new
a.is_a? a.singleton_class                  # true
a.singleton_class.superclass == A          # true
# similarly
A.is_a? A.singleton_class                  # true
A.singleton_class.ancestors.include? Class # true 
class << a
  def foobar
  end
end
a.foobar
def a.foobar
  # same effect as above
end
a.foobar
class << A
  # you opened the singleton class, so self is A.singleton_class
  def self.m3
    puts "im m3"
  end
end
A.singleton_class.m3
# in m3