masterweily
masterweily

Reputation: 736

A way to dynamically add fields to struct in ruby

Lets say I have this struct with the fields: first_name, last_name, phone

Contact = Struct.new :first_name, :last_name, :phone

now i want to dynamically add another field named :email.

is there an easy way to do this?

Upvotes: 2

Views: 2534

Answers (1)

Jerome Dalbert
Jerome Dalbert

Reputation: 10405

Ruby's OpenStruct seems best fit for this use case.

require 'ostruct'
...
contact = OpenStruct.new(first_name: "John", last_name: "Doe", phone: "XXXXXXX")

And later you can do

contact.email = "[email protected]"

Upvotes: 8

Related Questions