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

ruby-on-rails – 当你说Ruby是反射的时,这主要是指“鸭子打字”

发布时间:2020-12-17 04:03:01 所属栏目:百科 来源:网络整理
导读:我正在阅读描述 Ruby的文本,它说如下: Ruby is considered a “reflective” language because it’s possible for a Ruby program to analyze itself (in terms of its make-up),make adjustments to the way it works,and even overwrite its own code wi
我正在阅读描述 Ruby的文本,它说如下:

Ruby is considered a “reflective”
language because it’s possible for a
Ruby program to analyze itself (in
terms of its make-up),make
adjustments to the way it works,and
even overwrite its own code with other
code.

我对这个术语“反思”感到困惑 – 这主要是谈论Ruby可以看一个变量的方式,并弄清楚它是一个整数还是一个字符串(鸭子打字),例如:

x = 3
x = "three" # Ruby reassigns x to a String type

解决方法

课程重新开放就是一个很好的例子.这是一个简单的例子:

class Integer
    def moxy
        if self.zero?
            self - 2
        elsif self.nonzero?
            self + 2          
        end      
    end  
end

puts 10.moxy

通过重新打开标准的Ruby类 – Integer – 并在其中定义一个名为’moxy’的新方法,我们可以直接对一个数字执行新定义的操作.在这种情况下,我已经定义了这个组成’moxy’的方法,如果它为零则从Integer中减去2,如果它非零,则加2.这使得moxy方法可用于Ruby中的Integer类的所有对象. (这里我们使用’self’关键字来获取整数对象的内容).

如您所见,它是Ruby的一个非常强大的功能.

编辑:一些评论者质疑这是否真的是reflection.在英语中,反思这个词指的是看你自己的想法.这当然也是编程反思的一个重要方面 – 使用像is_a,kind_of,instance_of这样的Ruby方法来执行运行时自检.但反射也指程序在运行时修改自身行为的能力.重新开放课程是其中一个重要的例子.它也被称为monkey patching.它并非没有风险,但我所做的只是在反思的背景下描述它,这是一个例子.

(编辑:李大同)

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

    推荐文章
      热点阅读