-
Notifications
You must be signed in to change notification settings - Fork 0
/
animals-oriented-on-objects.rb
135 lines (96 loc) · 2.11 KB
/
animals-oriented-on-objects.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
require 'pp'
# *** ANIMALS *****************************************************************
#-- file Animal.rb
class Animal
attr_accessor :name, :position, :color
def initialize(name)
@name = name
@position = 0
@stuff_in_belly = 0
@walk_increment = 1
@run_increment = 10
puts "Hello, I am a #{self.class.to_s.downcase} named #{self.name}!"
end
def talk
puts "#{self.class}: ..."
end
def walk
@position += @walk_increment
end
def run
@position += @run_increment
end
def feed
@stuff_in_belly += 1
puts "[Chewing on some stuff and happy...]"
self.poop if @stuff_in_belly > 3
end
def hungry?
if @stuff_in_belly < 2
true
else
false
end
end
protected
def poop
puts "[Too much stuff in belly... pooping...]"
@stuff_in_belly = 0
end
end
#-- file Dog.rb
class Dog < Animal
def initialize(name, color)
super(name)
@color = color
@run_increment = 20
end
def talk
puts "#{self.name}: Woof! woof!"
end
def fetch(what='stick')
puts "[#{self.name} is fetching the #{what.downcase}...]"
end
end
#-- file Sheep.rb
class Sheep < Animal
def talk
puts "#{self.name}: Beeeeee!"
end
end
# === Dog =====================================================================
# --- Create a dog
dog = Dog.new('Bitzer', 'yellow')
pp dog
# --- Dog's properties (attributes)
puts "Our dog's name is '#{dog.name}'."
puts "And his color is #{dog.color}."
# --- Make the dog do something
puts "> Talk, Bitzer!"
dog.talk
puts "> Fetch, Bitzer!"
dog.fetch
dog.fetch('Ball')
puts "> Walk, Bitzer!"
dog.walk
puts "Dog is at position: #{dog.position}."
puts "> Run, Bitzer!"
dog.run
puts "Dog is at position: #{dog.position}."
puts "> Have a snack, Bitzer!"
dog.feed
puts dog.hungry?
dog.feed
dog.feed
puts dog.hungry?
# dog.poop
dog.feed
puts "\n---\n\n"
# === Sheep ===================================================================
sheep = Sheep.new('Shaun')
pp sheep
sheep.talk
puts sheep.position
sheep.run
puts sheep.position
# sheep.fetch # => NoMethodError