-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotes-and-practice.rb
123 lines (98 loc) · 2.32 KB
/
notes-and-practice.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
# puts a[5]
def mysum (arr, n)
if n > arr.length
return -1
end
index = arr.length-n
sum=0
loop do
sum += arr[index]
index += 1
break if index == arr.length
end
return sum
end
puts mysum([3,40,5,70,10],10)
puts mysum([1,2,3,4,5],2)
#display.
puts "The Ruby Language".length
#shallow copy.
person1 = "Tony"
person2 = person1
#deep copy.
person3 = person1.dup
#check output.
person1[0] = "R"
puts person1
puts person2
puts person3
puts person1[-1]
#create array.
b1 = Array.new
b2 = [1, 2, 3]
#associative arrays
hashName = {
"key" => "value"
}
puts hashName.length
puts hashName["key"] #by name NOT index
#associative arrays - add
hashName["key2"] = "value2"
#associative arrays - delete
hashName.delete_if{
|key, value| key == "key2"
}
#associative arrays - iterate
hashName.each_pair do |key, value|
puts "#{key} : #{value}"
end
hashName.each do |key, value| #same thing
puts "#{key} : #{value}"
end
hashName.each_key do |key|
puts "#{key}"
end
#puts vs. print
puts "adds new line"
puts ": demonstration 1"
print "does not add new line"
puts " : demonstration 2"
puts ": demonstration 3"
#include module in SubClassName. #NOTE: This is just the structure to cover different concepts, does not work.
require "./ClassNameFile.rb" #file in directory with ClassName
class SubClassName < ClassName
@@new_class_var = 0
attr_accessor :b #to avoid set/get methods.
def initialize (a, b)
super(a)
@b = b
@@new_class_var += 1
end
def to_s
return "instance variable @a is #@a instance variable @b is #@b"
end
def class_var_total
return "class variable @@new_class_var is #@@new_class_var"
end
end
example = SubClassName.new(5, 3)
puts example.to_s
puts example.class_var_total
example2 = SubClassName.new(3, 5)
def example2.whoAmI
return "you are a subclass"
end
puts example2.whoAmI
puts
#naming conventions
ModuleName #collection of constants, methods. Cant generate instances.
ClassName #may generate objects, and have instance variables.
$global_variable
@@class_variable
CONSTANT_NAME
ConstantName
Constant_Name
@instance_variable
:symbol_name
method_name
local_variable