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!