Created
April 25, 2009 00:39
-
-
Save mboeh/101426 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# 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