加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 03:28:27 所属栏目:百科 来源:网络整理
导读:以下是 Why’s Poignant Guide to Ruby Chapter 6的Ruby代码片段,他试图在Ruby中演示元编程: # Get a metaclass for this classdef self.metaclass; class self; self; end; end 我对Ruby并不熟悉,但这是扩展形式的样子吗? def self.metaclass def self.se
以下是 Why’s Poignant Guide to Ruby Chapter 6的Ruby代码片段,他试图在Ruby中演示元编程:

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

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

def self.metaclass
    def self.self
    end
end

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

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

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

如果我理解正确,这段代码会给@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

在使用中:

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

解决方法

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

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

Read around the ‘net对象的“元类”是什么.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读