Skip to content

Instantly share code, notes, and snippets.

@mboeh
Created April 25, 2009 00:39
Show Gist options
  • Save mboeh/101426 to your computer and use it in GitHub Desktop.
Save mboeh/101426 to your computer and use it in GitHub Desktop.
# Ruby syntax never fails to amaze me, casefile whatever.
# Yes, this could be accomplished more elegantly another way. But this is fun.
require 'ostruct'
def DStruct(*a)
klass = Struct.new(*a)
defs = Hash.new
yield defs
klass.send :define_method, :initialize do |*a|
super
for attrib, dval in defs
self.send("#{attrib}=", dval) if self.send(attrib).nil?
end
end
return klass
end
class Person <
DStruct(:first, :last, :job) do |defaults|
defaults[:first] = "Joe"
defaults[:last] = "Bloggs"
defaults[:job] = "Comic Gravedigger"
end
def describe
"#{first} #{last}, the #{job}"
end
end
dude = Person.new("Ann")
puts dude.describe # ==> "Ann Bloggs, the Comic Gravedigger"
dude = Person.new(nil, nil, "Social Media Expert")
puts dude.describe # ==> "Joe Bloggs, the Social Media Expert"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment