gpt4 book ai didi

Ruby——理解符号

转载 作者:数据小太阳 更新时间:2023-10-29 07:38:33 26 4
gpt4 key购买 nike

我在理解符号在我的代码中的工作方式时遇到了一些困难。我知道它们本质上是不可变的字符串,但我不完全理解符号如何自动“识别”我代码的其他部分。

例如,在下面的程序中,我将两个方法对象传递给我的 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,5)

我不理解的另一个符号示例是关于封装的——attr_readerattr_writerattr_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?

这与符号无关。您甚至可以执行 method('plus'),您将获得与 method(:plus) 相同的结果。

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)。他们只是获取传递的符号的值,并创建相关的方法。

关于Ruby——理解符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6285535/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com