Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lucaswinningham/c73de6e0d202c4e73ca515958d787df9 to your computer and use it in GitHub Desktop.
Save lucaswinningham/c73de6e0d202c4e73ca515958d787df9 to your computer and use it in GitHub Desktop.
How to create a class dynamically in Ruby

Taken from this answer on StackOverflow

name = "Person"
attributes = [:name, :age]

class MyBaseClass; end

klass = Class.new(MyBaseClass) do
  ATTRIBUTES = attributes

  attr_accessor *ATTRIBUTES

  def initialize(*args)
    raise ArgumentError, "Too many arguments" if args.size > ATTRIBUTES.size

    ATTRIBUTES.zip(args) do |attr, val|
      send "#{attr}=", val
    end
  end
end

Object.const_set name, klass
Person.new("John Doe", 42) # => #<Person:0x007f934a975830 @name="John Doe", @age=42> 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment