Ruby - Symbols of Understanding

I am having trouble understanding how characters work in my code. I understand that they are essentially immutable strings, but I don’t quite understand how characters automatically recognize other parts of my code.

For example, in the program below, I pass two object methods into my math_machine methods, but for this I use a character representing their name. How does Ruby know what I mean by these methods?

def plus x,y return x+y end def minus x,y return xy 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 characters that I don’t understand is about encapsulation - how attr_reader , attr_writer and attr_accessor know that the next character refers to an instance variable in my program?

If someone can explain to me the mysterious nature of characters in Ruby (what happens behind the scenes), that would be awesome!

+4
source share
1 answer

For example, in the program below, I pass two method objects to my math_machine, but for this I use a symbol denoting their name. How does Ruby know what I mean by those methods?

This has nothing to do with symbols. You can even make method('plus') , and get the same result as the 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 characters that I don’t understand is about encapsulation - how do attr_reader, attr_writer and attr_accessor know that this character follows an instance variable in my program?

These methods are designed to provide readers, writers, and accessories with the (r + w) instance method. They simply take the value of the passed character and create the appropriate methods.

+1
source

All Articles