这个 ruby 自定义访问器是如何工作的
因此,class_eval 中的以下方法动态地为运行时定义的属性创建访问器。例如,它可用于创建具有从配置文件读取的属性的配置对象(并且在运行时之前未知)。除了 else 分支之外,我理解所有内容。如果我是正确的,如果 *val 中传递了一个值,则 else 分支将返回属性值 (val[0])。然而,按照其编写方式,如果 *var 中传递了多个值,我希望它返回一个数组 (val)。特别是,如果我有类似以下内容:
value = 5
那么通过阅读代码,我预计 @value 为 [=,5]
。但是,@value
返回 5,而不是数组 [=,5]。这怎么可能?
class Module
def dsl_accessor(*symbols)
symbols.each do |sym|
class_eval %{
def #{sym}(*val)
if val.empty?
@#{sym}
else
@#{sym} = val.size == 1 ? val[0] : val
end
end
}
end
end
end
So the method below in class_eval dynamically creates accessors for attributes defined at runtime. It can be used, for example, to create configuration objects with attributes read from a config file (and unknown until runtime). I understanding all of it except for the else branch. If I am correct the else branch returns the attribute value (val[0]) if there is one value passed in *val. However the way its written I would expect it to return an array (val) if there is more then one value passed in *var. In particular, if I have something like the following:
value = 5
then from reading the code I would expect @value to be [=,5]
. However @value
returns 5 and not the array [=,5]. How is this possible?
class Module
def dsl_accessor(*symbols)
symbols.each do |sym|
class_eval %{
def #{sym}(*val)
if val.empty?
@#{sym}
else
@#{sym} = val.size == 1 ? val[0] : val
end
end
}
end
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
等号不是方法的参数,而是方法名称的一部分。实际上,您可以这样调用赋值:
因此,只有整数 5 是该函数的参数。
An equals sign is not an argument for the method, it's a part of the method name. Actually you can call an assignment like this:
So only the integer 5 is an argument for the function.