-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathderived_value.rb
More file actions
56 lines (45 loc) · 1.74 KB
/
Copy pathderived_value.rb
File metadata and controls
56 lines (45 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# Derived value
# In Ruby, you can create derived values by defining methods that calculate a value based on the instance variables of an object.
# This allows you to create values that are not stored directly in the object but can be calculated when needed.
class Rectangle
attr_reader :length, :width
def initialize(length, width)
@length = length
@width = width
end
# derived value method to calculate the area of the rectangle based on the length and width instance variables.
def area
@length * @width
end
end
rectangle = Rectangle.new(5, 3)
puts "Length: #{rectangle.length}"
puts "Width: #{rectangle.width}"
puts "Area: #{rectangle.area}"
# Other example using derived shopping cart total price based on the items in the cart.
class ShoppingCart
attr_reader :items
# empty array to hold the items in the cart
def initialize
@items = []
end
# method to add items to the cart
def add_item(name, price)
@items << { name: name, price: price}
end
# derived value method to calculate the total price of the items in the cart based on the price of each item.
def total_price
# reduce method to iterate through the items in the cart and calculate the total price by summing up the price of each item.
# the initial value of total is set to 0 because if we did'nt set the initial value, the first item's price would be used as the initial value
# wich means is incorrect because the first item's is a hash.
@items.reduce(0) do |total, item|
total + item[:price]
end
end
end
cart = ShoppingCart.new
cart.add_item("Book", 10)
cart.add_item("Pen", 2)
cart.add_item("Notebook", 5)
puts "Items in cart: #{cart.items.map { |item| item[:name] }.join(", ")}"
puts "Total price: $#{cart.total_price}"