Skip to content

Commit

Permalink
Replace Array with Object.
Browse files Browse the repository at this point in the history
  • Loading branch information
josemotanet committed May 29, 2013
1 parent d412059 commit f3d34d5
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
22 changes: 22 additions & 0 deletions replace-array-with-object/lib/after.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class Cart
attr_reader :products

def initialize products
@products = products.map { |product| Product.new *product }
end

def total
products.inject(0) { |sum, product| sum + product.price }
end

end

class Product
attr_reader :name, :color, :price

def initialize name, color, price
@name = name
@color = color
@price = price
end
end
14 changes: 14 additions & 0 deletions replace-array-with-object/lib/before.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class Cart
attr_reader :products

def initialize products
@products = products
end

def total
products.inject(0) { |sum, product|
sum + product[2]
}
end

end
10 changes: 10 additions & 0 deletions replace-array-with-object/test/test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,13 @@

require 'before' if ENV["BEFORE"]
require 'after' unless ENV["BEFORE"]

describe Cart do
it "has a list of items" do
Cart.new([
[ "Sweater" , "Pink" , 5.0 ],
[ "Trousers" , "Blue" , 8.0 ],
[ "Golf Club" , "Gray" , 12.0 ]
]).total.must_equal 25.0
end
end

0 comments on commit f3d34d5

Please sign in to comment.