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

Ruby – 理解符号

发布时间:2020-12-17 01:59:24 所属栏目:百科 来源:网络整理
导读:我在理解符号在代码中的工作方式时遇到了一些麻烦.我知道它们本质上是不可变的字符串,但我不完全理解符号如何自动“识别”我的代码的其他部分. 例如,在下面的程序中,我将两个方法对象传递给我的math_machine方法,但为了这样做,我使用了一个代表其名称的符号.
我在理解符号在代码中的工作方式时遇到了一些麻烦.我知道它们本质上是不可变的字符串,但我不完全理解符号如何自动“识别”我的代码的其他部分.

例如,在下面的程序中,我将两个方法对象传递给我的math_machine方法,但为了这样做,我使用了一个代表其名称的符号. Ruby如何知道我指的是那些方法?

def plus x,y
    return x+y
end

def minus x,y
    return x-y
end

def math_machine(code,x,y)
    code.call(x,y)
end

puts math_machine(method(:plus),5,5)
puts math_machine(method(:minus),5)

另一个我不理解的符号示例是关于封装 – attr_reader,attr_writer和attr_accessor如何知道后面的符号是指我程序中的实例变量?

如果有人能够向我解释Ruby中符号的神秘本质(幕后发生的事情)那将是非常棒的!

解决方法

For example,in the program below,I
pass two method objects to my
math_machine methods,but to do so I
use a symbol representing their name.
How does Ruby know that I am referring
to those methods?

这与符号无关.你甚至可以做方法(‘加’),你会得到与方法(加号)相同的结果.

irb(main):001:0> def plus
irb(main):002:1> end
=> nil
irb(main):003:0> method(:plus)
=> #<Method: Object#plus>
irb(main):004:0> method('plus')
=> #<Method: Object#plus>
irb(main):005:0> method('plus') == method(:plus)
=> true

Another example of symbols I don’t
understand is regarding encapsulation
— how do attr_reader,attr_writer,and attr_accessor know that the symbol
that follows refers to an instance
variable in my program?

这些方法旨在为实例方法提供读者,编写者和访问者(r w).他们只需要传递符号的值,并创建相关的方法.

(编辑:李大同)

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

    推荐文章
      热点阅读