Skip to content

Instantly share code, notes, and snippets.

@satoshun
Created April 7, 2013 02:44
Show Gist options
  • Save satoshun/5328675 to your computer and use it in GitHub Desktop.
Save satoshun/5328675 to your computer and use it in GitHub Desktop.
refactor, data to object
class CarryBack
def initialize
@buy_list = []
end
def add_item(price)
@buy_list.push price
end
def total
@buy_list.inject(0, :+)
end
end
c = CarryBack.new
c.add_item 100
c.add_item 200
p c.total
class Item
@@price = 0
def tax
@@price * 1.05
end
def get_price
@@price
end
end
class Meat < Item
@@name = "肉"
@@price = 200
end
class Rice < Item
@@name = "米"
@@price = 1000
end
class CarryBack2 < CarryBack
def add_item(obj)
@buy_list.push obj
end
def total_include_tax
@buy_list.inject(0){|sum, i| sum += i.tax}.to_i
end
def total
@buy_list.inject(0){|sum, i| sum += i.get_price}
end
end
c2 = CarryBack2.new
c2.add_item Rice.new
p c2.total
p c2.total_include_tax
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment