Skip to content

Instantly share code, notes, and snippets.

@FaisalAl-Tameemi
Created July 27, 2016 00:04
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 FaisalAl-Tameemi/d9a1239e368e2ed6b53a8a45488fa9b1 to your computer and use it in GitHub Desktop.
Save FaisalAl-Tameemi/d9a1239e368e2ed6b53a8a45488fa9b1 to your computer and use it in GitHub Desktop.
OOP Electronics Store Example
class Cellphone < Product
def initialize(name, price, brand)
super
end
end
class Customer
attr_reader :cart, :budget
def initialize(budget = 500)
@cart = []
@budget = budget.nil? ? 500 : budget
end
end
class Laptop < Product
attr_reader :size, :ram, :processor
def initialize(name, price, brand, specs)
super(name, price, brand)
@size = specs[:size]
@ram = specs[:ram]
@processor = specs[:processor]
end
end
class Product
attr_reader :name, :brand
attr_accessor :price
def initialize(name, price, brand)
@name = name
@price = price
@brand = brand
end
end
class Shop
attr_reader :name, :inventory, :sales
def initialize(name)
@name = name
@inventory = []
@sales = []
end
def find_inventory_product(product_to_find)
@inventory.find{|product|
product == product_to_find
}
end
def add_to_inventory(product)
@inventory.push(product)
# the more Ruby style way of pushing
# @inventory << product
end
def sell_item(product)
# return false if the product isn't found in inventory
return false if find_inventory_product(product).nil?
@sales.push(product) # add product to sales list
@inventory.delete(product) # remove product from inventory
product
end
def revenue
self.sales.inject(0){|sum, current_sale|
sum += current_sale.price
}
end
end
class Tv < Product
attr_reader :size
def initialize(name, price, brand, size)
super(name, price, brand)
@size = size
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment