Noah
Noah

Reputation: 516

Can I use metaprogramming to dynamically initialize a class?

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.

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.

Upvotes: 1

Views: 126

Answers (1)

Flexoid
Flexoid

Reputation: 4235

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

members *ListOfMembers

Upvotes: 3

Related Questions