-
Notifications
You must be signed in to change notification settings - Fork 105
/
strategy.rb
48 lines (40 loc) · 1.02 KB
/
strategy.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
# Define a family of algorithms, encapsulate each one, and make them
# interchangeable.
class Hero
attr_reader :damage, :health, :skills
attr_accessor :printer
def initialize(printer)
@damage = 10
@health = 5
@printer = printer
@skills = [:stealth, :driving, :intimidation]
end
def print_stats
if block_given?
yield(damage, health, skills)
else
printer.print(damage, health, skills)
end
end
end
class BattleStats
def print(damage, health, skills)
"Damage: #{damage}\nHealth: #{health}"
end
end
class SkillStats
def print(damage, health, skills)
skills.inject(""){ |result, skill| result + skill.to_s.capitalize + "\n" }
end
end
# Usage
Hero.new(BattleStats.new).print_stats
# => Damage: 10
# Health: 5
Hero.new(SkillStats.new).print_stats
# => Stealth
# Driving
# Intimidation
Hero.new(any_printer).print_stats do |damage, health, skills|
"Looks: I'm printing a customize message about my hero with damage #{damage} and number of skills: #{skills.size}"
end