-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path6_objects.rb
More file actions
96 lines (66 loc) · 1.75 KB
/
6_objects.rb
File metadata and controls
96 lines (66 loc) · 1.75 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
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
# In an object oriented language we model real world objects using classes
# Every object has attributes (instance variables) and capabilities (methods)
class Animal
# Called when an Animal object is created
# You should set default values here
def initialize
puts "Creating a New Animal"
end
def set_name(new_name)
# Sets the value for an instance variable
@name = new_name
end
def get_name
@name
end
# Provides another way to get the value for name
def name
@name
end
# Provides another way to set the value for name
def name=(new_name)
# We can eliminate bad input in our setters
if new_name.is_a?(Numeric)
puts "Name Can't Be a Number"
else
@name = new_name
end
end
end
# Creates a new Animal object
cat = Animal.new
# Sets the Animals name
cat.set_name("Peekaboo")
# get_name returns the value of name
puts cat.get_name
# Using the alternative way of getting the name value
puts cat.name
# Using the alternative way of setting a value for name
cat.name = "Sophie"
puts cat.name
class Dog
# Shortcut for creating all getter functions
attr_reader :name, :height, :weight
# Shortcut for creating all setter functions
attr_writer :name, :height, :weight
# Creates setter and getter methods (Use this One)
attr_accessor :name, :height, :weight
def bark
return "Generic Bark"
end
end
rover = Dog.new
rover.name = "Rover"
puts rover.name
puts rover.bark
# When you inherit from another class you get all its methods and variables
# You can only inherit from one class
class GermanShepard < Dog
# You can overwrite methods as you need
def bark
return "Loud Bark"
end
end
max = GermanShepard.new
max.name = "Max"
printf "%s goes %s \n", max.name, max.bark()