-
Notifications
You must be signed in to change notification settings - Fork 0
/
polygons.rb
148 lines (117 loc) · 2.36 KB
/
polygons.rb
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# Objetivos de aprendizaje:
#
# 1) Declarar una clase en Ruby
# 2) Agregar un constructor
# 3) Definir atributos y su acceso (reader, writer, accessor)
# 4) Agregar métodos
# 5) Controlar el acceso a métodos
# 6) Herencia de clases
class Polygon
attr_reader :sides
attr_accessor :color
def initialize(sides, color = "black")
@sides = sides
@color = color
end
def area
end
def perimeter
end
def eql?(other_polygon)
@sides == other_polygon.sides and @color == other_polygon.color
end
def hash
@sides.hash + @color.hash
end
end
class Circle < Polygon
attr_accessor :radius
def self.pi
3.14159265359
end
def initialize(radius)
super(0)
@radius = radius
end
def area
pi * @radius * @radius
end
def perimeter
2 * pi * @radius
end
def eql?(other_circle)
super and @radius == other_circle.radius
end
def hash
super + @radius.hash
end
end
class Triangle < Polygon
attr_accessor :base
attr_accessor :height
def initialize(base, height, color = nil)
if color == nil
super(3)
else
super(3, color)
end
@base = base
@height = height
end
def area
(@base * @height) / 2.0
end
def perimeter
a = @base / 2
b = @height
h = Math.sqrt((a * a) + (b * b))
@base + (2 * h)
end
def eql?(other_triangle)
super and @base == other_triangle.base and @height == other_triangle.height
end
def hash
super + @base.hash + @height.hash
end
end
class SidesPolygon < Polygon
attr_accessor :side_length
def initialize(side_length, sides, color)
super(sides, color)
@side_length = side_length
end
def perimeter
@side_length * @sides
end
def eql?(other_polygon)
super and @side_length == other_polygon.side_length
end
def hash
@side_length.hash + super
end
end
class Square < SidesPolygon
def initialize(side_length)
super(side_length, 4, "red")
end
def area
@side_length * @side_length
end
end
class Pentagon < SidesPolygon
def initialize(side_length, color)
super(side_length, 5, color)
end
def area
a = @side_length
0.25 * Math.sqrt(5 * (5 + 2 * Math.sqrt(5))) * (a * a)
end
end
class Hexagon < SidesPolygon
def initialize(side_length, color)
super(side_length, 6, color)
end
def area
((3 * Math.sqrt(3)) / 2) * @side_length * @side_length
end
end