Naming methods as Ruby variable invocation methods

Hi, I am starting very.

I think I understand how attr_accessor (below) works. and "setter" is the name=(name) method. and I know that this method is equivalent to assignment: name = "john" . because "=" is a method that takes an argument and assigns this argument to any object that calls it. (although I don’t understand how "name" can be considered an object, since it is assigned to the object)

, so my question is: how can you assign a variable calling the method as the name of the method? It seems that I missed something.

 class Person def name @name end def name=(name) @name = name end end 
0
ruby attr-accessor
source share
1 answer

so my question is: how can you assign a variable calling the method as the name of the method? It seems that I missed something.

Not. In this code

 def name=(name) @name = name end 

name= not variable name calls method = . method name= .

Edit:

In the above snippet of code def paired with the ending end is a method definition.

 def method_name(param1, param2) # method body end 

On the same line as def , there can only be a method name, optional parentheses and a list of parameters. By definition, having a "variable calling a method" on this line would be illegal. So in your code name= is the name of the method.

+1
source share

All Articles