Skip to content

Instantly share code, notes, and snippets.

@jimsynz
Created August 25, 2014 22:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimsynz/1786dc357ef75a713468 to your computer and use it in GitHub Desktop.
Save jimsynz/1786dc357ef75a713468 to your computer and use it in GitHub Desktop.
Struct using keyword args (actually, really just a hash).
class KStruct
def self.new *attr_names
Class.new(Struct) do
attr_accessor *attr_names
end
end
class Struct
def initialize args
args.each do |key,value|
public_send "#{key}=", value
end
end
end
end
klass = KStruct.new *%i| name age gender |
puts klass.new(name: 'Marty', age: 17, gender: 'Male').inspect
# => #<#<Class:0x007ffb89a74ea0>:0x007ffb89a74bd0 @name="Marty", @age=17, @gender="Male">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment