Peter Al
Peter Al

Reputation: 378

Defining a Struct with attributes determined at runtime

I've noticed Ruby's philosophy of keeping as many things flexible in the run time as possible.

Here is a typical (for the best of my knowledge) Ruby struct definition:

    Person = Struct.new("Person", :name, :address)
    Person.new("John", "Chicago, IL")

My question is, is it possible to define a structure in run-time when the list of structure fields / members is also defined in the run time? Something that would look like this:

    Person = Struct.new("Person", list_of_structure_fields)

Upvotes: 1

Views: 132

Answers (2)

steenslag
steenslag

Reputation: 80065

OpenStruct is designed to do just that:

require 'ostruct'
h = {name: "John", address: "Chicago, IL"}
person = OpenStruct.new(h)
puts person.name #=> John
person.age  = 35 # freely add fields and values 

Upvotes: 3

Michael Kohl
Michael Kohl

Reputation: 66837

You can just splat an array:

fields = [:name, :address]
Person = Struct.new("Person", *fields)
Person.new("John", "Chicago, IL")
#=> #<struct Struct::Person name="John", address="Chicago, IL">

This allows you to do some fun things:

person = {name: "John", address: "Chicago, IL"}
Person = Struct.new("Person", *person.keys)
Person.new(*person.values)
#=> #<struct Struct::Person name="John", address="Chicago, IL">

Upvotes: 5

Related Questions