-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunderstanding_classes_and_objects.txt
More file actions
63 lines (40 loc) · 2.04 KB
/
understanding_classes_and_objects.txt
File metadata and controls
63 lines (40 loc) · 2.04 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
1. You can get stuff out of a hash by calling the hash, with the key in square brackets []:
---
puts hash_name['key']
---
2. You can get stuff out of a module by requiring the module, then calling it and the function you want to use with a .
---
require "./module_name.rb"
module_name.function()
---
3. You can access variables in a similar way, but using :: instead of .
---
require "./module_name.rb"
module_name::variable
---
So the key idea here is the same, you are using some code to hold things, and you can pull things out of it in a similar way, with [ ], . or ::, The tutuorial says this is takign a key=value style container, then getting something out of it by using the key's name.
---
hash['key']
module.function
module::variable
---
Classes work the same as modules, but there is a lot more complicated stuff going on.
Modules can only be used once, whereas classes can be used many, many times. In ex40.rb, you have an "instance variable" called tangerine and a function called apple.
To use a class, you have to do something similar to "require" for modules. This is called instatiate, which really just means 'create'. You would do this y calling the class's 'new' function.
--
thing = MyStuff.new()
thing.apple()
puts thing.tangerine
---
When you run something like the above, Ruby will craft an empty object with all the functions defined in the original class (make a copy of the empty class). @ means this object, $ means global. SO the @tangerine in the code refers to "the variable in this object called tangerine". Finally, we'll assign this object to a variable so we can use it, and call it later in the code if needed.
Doing the above gives you a copy of the class to use as a blueprint for your new code. When you do a similar thign with the module, you are using that module, of which there is only one.
We have elarned three ways o get things from other, bigger things.
hash/dict style
mystuff['apples']
module style
My_stuff.apples()
puts Mystuff::TANGERINE
class style
thing = MyStuff.new()
thing.apples()
puts thing.tangerines