这个 ruby​​ 自定义访问器是如何工作的

发布于 2024-10-09 12:19:14 字数 741 浏览 8 评论 0原文

因此,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

抠脚大汉 2024-10-16 12:19:14

等号不是方法的参数,而是方法名称的一部分。实际上,您可以这样调用赋值:

value=(5)

因此,只有整数 5 是该函数的参数。


class Module
    def dsl_accessor(*symbols)
        symbols.each do |sym|
            class_eval %{
                def #{sym}
                  @#{sym}
                end
                def #{sym}=(val)
                  @#{sym} = val
                end
            }
        end
    end
end

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:

value=(5)

So only the integer 5 is an argument for the function.


class Module
    def dsl_accessor(*symbols)
        symbols.each do |sym|
            class_eval %{
                def #{sym}
                  @#{sym}
                end
                def #{sym}=(val)
                  @#{sym} = val
                end
            }
        end
    end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文