Ruby -- understanding symbols
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_acce开发者_如何转开发ssor
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!
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?
This has nothing to do with symbols. You can even do method('plus')
and you'll get the same result as 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?
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.
精彩评论