-
Notifications
You must be signed in to change notification settings - Fork 12
/
iterator.cr
40 lines (32 loc) · 912 Bytes
/
iterator.cr
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
# The iterator pattern is a design pattern that provides a means for
# the elements of an aggregate object to be accessed sequentially without
# knowledge of its structure. This allows traversing of lists, trees and
# other structures in a standard manner.
class Fighter
getter name, weight
def initialize(@name : String, @weight : Int32)
end
end
class Tournament
include Enumerable(Fighter)
def initialize
@fighters = [] of Fighter
end
def <<(fighter)
@fighters << fighter
end
def each
@fighters.each { |fighter| yield fighter }
end
end
# Sample
tournament = Tournament.new.tap do |t|
t << Fighter.new "Jax", 150
t << Fighter.new "Liu Kang", 84
t << Fighter.new "Scorpion", 95
t << Fighter.new "Sub-Zero", 95
t << Fighter.new "Smoke", 252
end
p tournament.select { |fighter| fighter.weight > 100 }
.map { |fighter| fighter.name }
# ["Jax", "Smoke"]