Metaprogramming in Ruby: It’s All About the Self

本文深入探讨了Ruby元编程的核心概念,通过多个代码示例解释了如何在Ruby中定义类和对象的方法。文章揭示了在不同上下文中如何利用`self`来实现方法定义的灵活性,并解析了`class_eval`和`instance_eval`等方法的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

After writing my last post on Rails plugin idioms, I realized that Ruby metaprogramming, at its core, is actually quite simple.

It comes down to the fact that all Ruby code is executed code–there is no separate compile or runtime phase. In Ruby, every line of code is executed against a particular self . Consider the following five snippets:

class

 Person
  def

 self

.species


    "Homo Sapien"


  end


end


 
class

 Person
  class

 <<

 self


    def

 species
      "Homo Sapien"


    end


  end


end


 
class

 <<

 Person
  def

 species
    "Homo Sapien"


  end


end


 
Person.instance_eval

 do


  def
   species
    "Homo Sapien"


  end


end


 
def

 Person.species


  "Homo Sapien"


end

All five of these snippets define a Person.species that returns Homo Sapien . Now consider another set of snippets:

class

 Person
  def

 name
    "Matz"


  end


end


 
Person.class_eval

 do


  def

 name
    "Matz"


  end


end

These snippets all define a method called name on the Person class. So Person.new.name will return “Matz”. For those familiar with Ruby, this isn’t news. When learning about metaprogramming, each of these snippets is presented in isolation: another mechanism for getting methods where they “belong”. In fact, however, there is a single unified reason that all of these snippets work the way they do.

First, it is important to understand how Ruby’s metaclass works. When you first learn Ruby, you learn about the concept of the class, and that each object in Ruby has one:

class

 Person
end


 
Person.class

 #=> Class


 
class

 Class


  def

 loud_name
    "#{name.upcase}!"


  end


end


 
Person.loud_name

 #=> "PERSON!"

Person is an instance of Class , so any methods added to Class are available on Person as well. What they don’t tell you, however, is that each object in Ruby also has its own metaclass , a Class that can have methods, but is only attached to the object itself.

matz = Object

.new


def

 matz.speak


  "Place your burden to machine's shoulders"


end

What’s going on here is that we’re adding the speak method to matz ’s metaclass , and the matz object inherits from its metaclass and then Object . The reason this is somewhat less clear than ideal is that the metaclass is invisible in Ruby:

matz = Object

.new


def

 matz.speak


  "Place your burden to machine's shoulders"


end


 
matz.class

 #=> Object

In fact, matz ’s “class” is its invisible metaclass. We can even get access to the metaclass:

metaclass = class

 <<

 matz; self

; end


metaclass.instance_methods

.grep

(

/

speak/

)

 #=> ["speak"]

At this point in other articles on this topic, you’re probably struggling to keep all of the details in your head; it seems as though there are so many rules. And what’s this class << matz thing anyway?

It turns out that all of these weird rules collapse down into a single concept: control over the self in a given part of the code. Let’s go back and take a look at some of the snippets we looked at earlier:

class

 Person
  def

 name
    "Matz"


  end


 
  self

.name

 #=> "Person"


end

Here, we are adding the name method to the Person class. Once we say class Person , the self until the end of the block is the Person class itself.

Person.class_eval

 do


  def

 name
    "Matz"


  end


 
  self

.name

 #=> "Person"


end

Here, we’re doing exactly the same thing: adding the name method to instances of the Person class. In this case, class_eval is setting the self to Person until the end of the block. This is all perfectly straight forward when dealing with classes, but it’s equally straight forward when dealing with metaclasses:

def

 Person.species


  "Homo Sapien"


end


 
Person.name

 #=> "Person"

As in the matz example earlier, we are defining the species method on Person ’s metaclass. We have not manipulated self , but you can see using def with an object attaches the method to the object’s metaclass.

class

 Person
  def

 self

.species


    "Homo Sapien"


  end


 
  self

.name

 #=> "Person"


end

Here, we have opened the Person class, setting the self to Person for the duration of the block, as in the example above. However, we are defining a method on Person ’s metaclass here, since we’re defining the method on an object (self ). Also, you can see that self.name while inside the person class is identical to Person.name while outside it.

class

 <<

 Person
  def

 species
    "Homo Sapien"


  end


 
  self

.name

 #=> ""


end

Ruby provides a syntax for accessing an object’s metaclass directly. By doing class << Person , we are setting self to Person ’s metaclass for the duration of the block. As a result, the species method is added to Person ’s metaclass, rather than the class itself.

class

 Person
  class

 <<

 self


    def

 species
      "Homo Sapien"


    end


 
    self

.name

 #=> ""


  end


end

Here, we combine several of the techniques. First, we open Person , making self equal to the Person class. Next, we do class << self , making self equal to Person ’s metaclass. When we then define the species method, it is defined on Person ’s metaclass.

Person.instance_eval

 do


  def

 species
    "Homo Sapien"


  end


 
  self

.name

 #=> "Person"


end

The last case, instance_eval , actually does something interesting. It breaks apart the self into the self that is used to execute methods and the self that is used when new methods are defined. When instance_eval is used, new methods are defined on the metaclass , but the self is the object itself.

In some of these cases, the multiple ways to achieve the same thing arise naturally out of Ruby’s semantics. After this explanation, it should be clear that def Person.species , class << Person; def species , and class Person; class << self; def species aren’t three ways to achieve the same thing by design , but that they arise out of Ruby’s flexibility with regard to specifying what self is at any given point in your program.

On the other hand, class_eval is slightly different. Because it take a block, rather than act as a keyword, it captures the local variables surrounding it. This can provide powerful DSL capabilities, in addition to controlling the self used in a code block. But other than that, they are exactly identical to the other constructs used here.

Finally, instance_eval breaks apart the self into two parts, while also giving you access to local variables defined outside of it.

In the following table, defines a new scope means that code inside the block does not have access to local variables outside of the block.

mechanismmethod resolutionmethod definitionnew scope?
class PersonPersonsameyes
class << PersonPerson’s metaclasssameyes
Person.class_evalPersonsameno
Person.instance_evalPersonPerson’s metaclassno

Also note that class_eval is only available to Modules (note that Class inherits from Module) and is an alias for module_eval . Additionally, instance_exec , which was added to Ruby in 1.8.7, works exactly like instance_eval , except that it also allows you to send variables into the block.

UPDATE: Thank you to Yugui of the Ruby core team for correcting the original post , which ignored the fact that self is broken into two in the case of instance_eval .

JFM7VX690T型SRAM型现场可编程门阵列技术手册主要介绍的是上海复旦微电子集团股份有限公司(简称复旦微电子)生产的高性能FPGA产品JFM7VX690T。该产品属于JFM7系列,具有现场可编程特性,集成了功能强大且可以灵活配置组合的可编程资源,适用于实现多种功能,如输入输出接口、通用数字逻辑、存储器、数字信号处理和时钟管理等。JFM7VX690T型FPGA适用于复杂、高速的数字逻辑电路,广泛应用于通讯、信息处理、工业控制、数据中心、仪表测量、医疗仪器、人工智能、自动驾驶等领域。 产品特点包括: 1. 可配置逻辑资源(CLB),使用LUT6结构。 2. 包含CLB模块,可用于实现常规数字逻辑和分布式RAM。 3. 含有I/O、BlockRAM、DSP、MMCM、GTH等可编程模块。 4. 提供不同的封装规格和工作温度范围的产品,便于满足不同的使用环境。 JFM7VX690T产品系列中,有多种型号可供选择。例如: - JFM7VX690T80采用FCBGA1927封装,尺寸为45x45mm,使用锡银焊球,工作温度范围为-40°C到+100°C。 - JFM7VX690T80-AS同样采用FCBGA1927封装,但工作温度范围更广,为-55°C到+125°C,同样使用锡银焊球。 - JFM7VX690T80-N采用FCBGA1927封装和铅锡焊球,工作温度范围与JFM7VX690T80-AS相同。 - JFM7VX690T36的封装规格为FCBGA1761,尺寸为42.5x42.5mm,使用锡银焊球,工作温度范围为-40°C到+100°C。 - JFM7VX690T36-AS使用锡银焊球,工作温度范围为-55°C到+125°C。 - JFM7VX690T36-N使用铅锡焊球,工作温度范围与JFM7VX690T36-AS相同。 技术手册中还包含了一系列详细的技术参数,包括极限参数、推荐工作条件、电特性参数、ESD等级、MSL等级、重量等。在产品参数章节中,还特别强调了封装类型,包括外形图和尺寸、引出端定义等。引出端定义是指对FPGA芯片上的各个引脚的功能和接线规则进行说明,这对于FPGA的正确应用和电路设计至关重要。 应用指南章节涉及了FPGA在不同应用场景下的推荐使用方法。其中差异说明部分可能涉及产品之间的性能差异;关键性能对比可能包括功耗与速度对比、上电浪涌电流测试情况说明、GTH Channel Loss性能差异说明、GTH电源性能差异说明等。此外,手册可能还提供了其他推荐应用方案,例如不使用的BANK接法推荐、CCLK信号PCB布线推荐、JTAG级联PCB布线推荐、系统工作的复位方案推荐等,这些内容对于提高系统性能和稳定性有着重要作用。 焊接及注意事项章节则针对产品的焊接过程提供了指导,强调焊接过程中的注意事项,以确保产品在组装过程中的稳定性和可靠性。手册还明确指出,未经复旦微电子的许可,不得翻印或者复制全部或部分本资料的内容,且不承担采购方选择与使用本文描述的产品和服务的责任。 上海复旦微电子集团股份有限公司拥有相关的商标和知识产权。该公司在中国发布的技术手册,版权为上海复旦微电子集团股份有限公司所有,未经许可不得进行复制或传播。 技术手册提供了上海复旦微电子集团股份有限公司销售及服务网点的信息,方便用户在需要时能够联系到相应的服务机构,获取最新信息和必要的支持。同时,用户可以访问复旦微电子的官方网站(***以获取更多产品信息和公司动态。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值