Metaprogramming in Ruby: It’s All About the Self

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 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
东南亚位于我国倡导推进的“一带一路”海陆交汇地带,作为当今全球发展最为迅速的地区之一,近年来区域内生产总值实现了显著且稳定的增长。根据东盟主要经济体公布的最新数据,印度尼西亚2023年国内生产总值(GDP)增长5.05%;越南2023年经济增长5.05%;马来西亚2023年经济增速为3.7%;泰国2023年经济增长1.9%;新加坡2023年经济增长1.1%;柬埔寨2023年经济增速预计为5.6%。 东盟国家在“一带一路”沿线国家中的总体GDP经济规模、贸易总额与国外直接投资均为最大,因此有着举足轻重的地位和作用。当前,东盟与中国已互相成为双方最大的交易伙伴。中国-东盟贸易总额已从2013年的443亿元增长至 2023年合计超逾6.4万亿元,占中国外贸总值的15.4%。在过去20余年中,东盟国家不断在全球多变的格局里面临挑战并寻求机遇。2023东盟国家主要经济体受到国内消费、国外投资、货币政策、旅游业复苏、和大宗商品出口价企稳等方面的提振,经济显现出稳步增长态势和强韧性的潜能。 本调研报告旨在深度挖掘东南亚市场的增长潜力与发展机会,分析东南亚市场竞争态势、销售模式、客户偏好、整体市场营商环境,为国内企业出海开展业务提供客观参考意见。 本文核心内容: 市场空间:全球行业市场空间、东南亚市场发展空间。 竞争态势:全球份额,东南亚市场企业份额。 销售模式:东南亚市场销售模式、本地代理商 客户情况:东南亚本地客户及偏好分析 营商环境:东南亚营商环境分析 本文纳入的企业包括国外及印尼本土企业,以及相关上下游企业等,部分名单 QYResearch是全球知名的大型咨询公司,行业涵盖各高科技行业产业链细分市场,横跨如半导体产业链(半导体设备及零部件、半导体材料、集成电路、制造、封测、分立器件、传感器、光电器件)、光伏产业链(设备、硅料/硅片、电池片、组件、辅料支架、逆变器、电站终端)、新能源汽车产业链(动力电池及材料、电驱电控、汽车半导体/电子、整车、充电桩)、通信产业链(通信系统设备、终端设备、电子元器件、射频前端、光模块、4G/5G/6G、宽带、IoT、数字经济、AI)、先进材料产业链(金属材料、高分子材料、陶瓷材料、纳米材料等)、机械制造产业链(数控机床、工程机械、电气机械、3C自动化、工业机器人、激光、工控、无人机)、食品药品、医疗器械、农业等。邮箱:market@qyresearch.com

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值