问题
hi i am very much a beginner.
i think i understand how the attr_accessor works (below). and the "setter" is the name=(name)
method. and i know that that method is equivalent to the assignment: name = "john"
. because "=" is a method that accepts an argument and assigns that argument to whatever object calls it. (though i don't understand how "name" could be considered an object as it is being assigned to an object)
so my question is: how can you assign a variable calling a method as a method name? It feels like I'm missing something..
class Person
def name
@name
end
def name=(name)
@name = name
end
end
回答1:
so my question is: how can you assign a variable calling a method as a method name? It feels like I'm missing something..
You don't. In this code
def name=(name)
@name = name
end
name=
isn't a variable name
calling a method =
. The name of the method is name=
.
Edit:
In the above code snippet the def
paired with a terminating end
constitutes a method definition.
def method_name(param1, param2)
# method body
end
On the same line as def
there can only be the method name, optional parentheses, and the param list. By definition having a "variable calling a method" in that line would be illegal. So in your code name=
is the method name.
来源:https://stackoverflow.com/questions/20932032/naming-methods-as-variables-calling-methods-ruby