Skip to content

Instantly share code, notes, and snippets.

@vtno
Last active July 14, 2017 11:39
Show Gist options
  • Save vtno/aaaa844cfa8d4d7979d17ffb986d54e8 to your computer and use it in GitHub Desktop.
Save vtno/aaaa844cfa8d4d7979d17ffb986d54e8 to your computer and use it in GitHub Desktop.
My attempt on mixing functional programming and good ol' OO in Ruby.
Item = Struct.new(:amount, :price, :name) do
def total_price
amount * price
end
end
Cart = Struct.new(:items) do
# total amount is finding sum of item amount
def total_amount
# a.k.a finding sum by item.amount function
sum_by_fuction(->(item) { item.amount })
end
# total price is finding sum of each item total price
def total_price
# a.k.a finding sum by item.total_price function
sum_by_fuction(->(item) { item.total_price })
end
def average_price
total_price / total_amount.to_f
end
# finding sum by function
def sum_by_fuction(fn)
items.reduce(0) { |sum, item| sum + fn.(item) }
end
end
def main
items = [Item.new(2, 20, 'apple'), Item.new(1, 30, 'orange')]
cart = Cart.new(items)
puts cart.items
puts cart.total_amount
puts cart.total_price
puts cart.average_price
end
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment