Created
August 25, 2014 22:27
-
-
Save jimsynz/1786dc357ef75a713468 to your computer and use it in GitHub Desktop.
Struct using keyword args (actually, really just a hash).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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