Ruby 的自我定义 [英] Ruby Definition of Self

查看:33
本文介绍了Ruby 的自我定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在读一本 Ruby 的书时发现了伪变量 self 的这个定义:

I was reading a Ruby book and came across this definition of the pseudo-variable self:

self - 当前的接收者对象方法

self - receiver object of the current method

有人可以分解这个定义并解释它的含义吗?一点都看不懂.

Could someone break down that definition and explain what it means? I don't understand any of it.

实际上,我对 self 是什么(及其应用程序)非常了解,并且我知道如何在 Google 上进行搜索.我只是想知道是否有人可以解释我引用的定义.具体来说.

I actually have a pretty good idea of what self is (and its applications) and I know how to search on Google. I was just wondering if someone could explain the definition I quoted. That specifically.

推荐答案

Ruby 和其他语言(例如 Smalltalk 和 Objective-C)更喜欢术语消息传递",而 Java 和 C++ 更喜欢方法调用".也就是说,Java 方式"是在对象上调用方法—在对象的上下文中运行代码 —而Ruby 方式"是向对象发送消息,对象通过运行其方法来响应该消息.

Ruby and other languages (such as Smalltalk and Objective-C) prefer the term "message passing", whereas Java and C++ prefer "method invocation". That is, the "Java way" is to call a method on an object — running code in the context of an object — whereas the "Ruby way" is to send an object a message, to which the object responds by running its method.

Ruby 会将 my_string.length 行描述为发送 my_string the length 消息".my_string 接收消息,因此称为接收者;在length 方法的定义中,self 将引用my_string.您可以使用 my_string.send(:length) 获得相同的效果.

Ruby would describe the line my_string.length as "sending my_string the length message". The my_string receives the message, and so is called the receiver; inside the definition of the length method, self would refer to my_string. You can get the same effect with my_string.send(:length).

从消息传递的角度考虑这个概念比从方法调用的角度考虑更灵活.要调用对象上的方法,该方法必须已预先定义,而您可以向对象发送一条消息,它可以选择动态处理(使用 respond_to?method_missing).这种灵活性是允许 Ruby 用作简洁的领域特定语言 (DSL) 的一方面.

Thinking of this concept in terms of message passing is more flexible than thinking in terms of method invocation. To invoke a method on an object, that method must have been pre-defined, whereas you can send an object a message that it can choose to handle dynamically (with respond_to? and method_missing). This flexibility is one aspect that allows Ruby to be used as concise domain-specific languages (DSL).

这篇关于Ruby 的自我定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆