我可以使用元编程来动态初始化类吗?

时间:2021-07-22 06:53:56

I have a script that creates a table like this:

我有一个脚本,可以创建一个这样的表:

class TableClass < Table  
    members :hello, :hallo, :halo  
end

This script creates a table with columns labeled "hello", "hallo", and "halo". I would like to dynamically declare the "members" portion so that I could use results generated by a different script to initialize this table. I am pretty new to Ruby and extremely new to the concept of metaprogramming, but I feel like this must be doable, I just don't know how yet.

此脚本创建一个表,其中的列标记为“hello”,“hallo”和“halo”。我想动态声明“成员”部分,以便我可以使用不同脚本生成的结果来初始化此表。我是Ruby的新手,对元编程的概念非常陌生,但我觉得这一定是可行的,我只是不知道如何。

After declaring:

ListOfMembers= [:hello, :hallo, :halo]

I have tried:

我努力了:

members ::ListOfMembers

and

members eval ::ListOfMembers.join(",")

to no avail, and I am unsure of what to search for to figure this out. All of the metaprogramming examples I have found revolve around class methods and don't seem relevant to this problem.

没有用,我不确定要搜索什么来解决这个问题。我发现的所有元编程示例都围绕类方法,似乎与此问题无关。

Scrapping this class structure would probably be the best way to do this, but I am trying to work with existing scripts as best I can.

删除此类结构可能是执行此操作的最佳方法,但我正尽力使用现有脚本。

1 个解决方案

#1


3  

Just add * to the array name and the method is passed each element as separate argument.

只需将*添加到数组名称,该方法将每个元素作为单独的参数传递。

members *ListOfMembers

#1


3  

Just add * to the array name and the method is passed each element as separate argument.

只需将*添加到数组名称,该方法将每个元素作为单独的参数传递。

members *ListOfMembers