Created
October 18, 2011 13:19
-
-
Save jasiek/1295394 to your computer and use it in GitHub Desktop.
Ruby pre-initialized struct
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 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