Skip to content

Instantly share code, notes, and snippets.

@jasiek
Created October 18, 2011 13:19
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 jasiek/1295394 to your computer and use it in GitHub Desktop.
Save jasiek/1295394 to your computer and use it in GitHub Desktop.
Ruby pre-initialized struct
class Basket < Struct.new(:entries)
def self.new(*args)
b = super(*args)
b.entries ||= []
b
end
def total
entries.inject(0.0) do |sum, entry|
sum += entry.subtotal
end
end
end
# This gives you the ability to pre-initialize a Struct object before doing anything else.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment