将方法命名为变量调用方法Ruby [英] naming methods as variables calling methods Ruby
问题描述
我非常初学者.
我想我了解attr_accessor的工作原理(如下).而设置者"是name=(name)
方法.而且我知道该方法等效于赋值:name = "john"
.因为"="是一种接受参数并将该参数分配给任何对象调用它的方法. (尽管我不明白在将名称"分配给对象时如何将其视为对象)
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
推荐答案
所以我的问题是:如何分配一个将方法调用为 方法名称?感觉好像我缺少什么..
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=
不是不是调用方法=
的变量name
.方法的名称是name=
.
name=
isn't a variable name
calling a method =
. The name of the method is name=
.
在上面的代码片段中,def
与终止的end
配对构成方法定义.
In the above code snippet the def
paired with a terminating end
constitutes a method definition.
def method_name(param1, param2)
# method body
end
与def
在同一行上,只能有方法名称,可选的括号和参数列表.根据定义,在该行中具有变量调用方法"将是非法的.因此,在您的代码中,name=
是方法名称.
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.
这篇关于将方法命名为变量调用方法Ruby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!