这个Ruby代码做了什么?:def self.metaclass; 班级"自我; 自; 结束; 结束

Lon*_*ler 5 ruby metaprogramming class object

以下是Ruby第6章"为什么的尖锐指南"中的Ruby代码片段,他试图在Ruby中演示元编程:

# Get a metaclass for this class
def self.metaclass; class << self; self; end; end
Run Code Online (Sandbox Code Playgroud)

我对Ruby并不熟悉,但这是扩展形式的样子吗?

def self.metaclass
    def self.self
    end
end
Run Code Online (Sandbox Code Playgroud)

至少这是我理解它的方式.但是,它仍然无法理解这段代码的作用.它的目的是什么?

在代码中,为什么添加这个:

arr.each do |a|
   metaclass.instance_eval do
     define_method( a ) do |val|
       @traits ||= {}
       @traits[a] = val
     end
   end
 end
Run Code Online (Sandbox Code Playgroud)

如果我理解正确,这段代码会给@traits添加一个具有给定名称和值的新值.那是对的吗?

感谢您的帮助,对于想要查看它的人来说,这是给我带来麻烦的完整源代码:

# The guts of life force within Dwemthy's Array
class Creature

# Get a metaclass for this class
def self.metaclass; class << self; self; end; end

# Advanced metaprogramming code for nice, clean traits
def self.traits( *arr )
 return @traits if arr.empty?

 # 1. Set up accessors for each variable
 attr_accessor *arr

 # 2. Add a new class method to for each trait.
 arr.each do |a|
   metaclass.instance_eval do
     define_method( a ) do |val|
       @traits ||= {}
       @traits[a] = val
     end
   end
 end

 # 3. For each monster, the `initialize' method
 #    should use the default number for each trait.
 class_eval do
   define_method( :initialize ) do
     self.class.traits.each do |k,v|
       instance_variable_set("@#{k}", v)
     end
   end
 end

end

# Creature attributes are read-only
traits :life, :strength, :charisma, :weapon
end
Run Code Online (Sandbox Code Playgroud)

在使用中:

class Dragon < Creature
    life( 1340 )     # tough scales
    strength( 451 )  # bristling veins
    charisma( 1020 ) # toothy smile
    weapon( 939 )    # fire breath
end
Run Code Online (Sandbox Code Playgroud)

Phr*_*ogz 5

class Foo
  def self.bar    # Create a method invoked by Foo.bar instead of Foo.new.bar
    42            # the return value of this method (value of last expression)
  end
end


class Foo
  def self.jim    # Another method on the class itself
    class << self # Change the 'self' to be the metaclass of the current object
      self        # Evaluate the current 'self' as the 'return value' of 
    end           # class<<self…end; and since this is the last expression in
  end             # the method, its value is the return value for the method
end
Run Code Online (Sandbox Code Playgroud)

简而言之:您所看到的定义了一个metaclassCreature类本身上命名的方法(而不是实例).当您运行此方法时,它会找到metaclass Creature并返回该方法.

在'网络周围阅读一个对象的"元类".

  • 如果您只想使用元类来定义方法,不,这不是必需的.但是如果你想出于其他原因(例如列出所有方法)来访问元类,那么该方法不会削减它.然而,切入它的是引入1.9.2 [`singleton_class`](http://www.ruby-doc.org/core-1.9.3/Object.html#method-i-singleton_class)执行相同功能的方法. (2认同)