Ruby——理解符号
我在理解符号在我的代码中如何工作时遇到了一些困难。我知道它们本质上是不可变的字符串,但我不完全理解符号如何自动“识别”代码的其他部分。
例如,在下面的程序中,我将两个方法对象传递给我的 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_reader
、attr_writer
和 attr_accessor
如何知道后面的符号引用到我的程序中的实例变量?
如果有人可以向我解释 Ruby 中符号的神秘本质(幕后发生的事情),那就太棒了!
I'm having a little trouble understanding how symbols work in my code. I understand that they are essentially immutable strings, but I don't fully understand how symbols automatically "recognize" other parts of my code.
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?
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)
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?
If someone could explain to me the mysterious nature of symbols in Ruby (what is going on behind the scenes) that would be awesome!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这与符号无关。您甚至可以执行
method('plus')
并且您将获得与 method(:plus) 相同的结果。这些方法旨在为实例方法提供读取器、写入器和访问器 (r+w)。他们只是获取传递的符号的值,并创建相关的方法。
This has nothing to do with symbols. You can even do
method('plus')
and you'll get the same result as method(:plus).These methods are meant to provide readers, writers, and accessors (r+w) to instance method. They just take the value of the symbol passed, and create the relevant methods.