This repository was archived by the owner on Dec 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
795 lines (694 loc) · 12.7 KB
/
index.html
File metadata and controls
795 lines (694 loc) · 12.7 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
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
<!DOCTYPE html>
<html>
<head>
<title>OOP</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<style type="text/css">
@import url(http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz);
@import url(http://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic);
@import url(http://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700,400italic);
body {
font-family: 'Droid Serif';
font-size: 1.5em;
}
h1, h2, h3 {
font-family: 'Yanone Kaffeesatz';
font-weight: normal;
}
.small {
font-size: 0.6em;
}
.remark-code, .remark-inline-code { font-family: 'Ubuntu Mono'; }
</style>
</head>
<body>
<textarea id="source">
class: center, middle
# OOP in RUBY
---
# Defining a simple class
```ruby
class Car
# code...
end
AnotherCar = Class.new do
# code...
end
```
???
класс это тоже класс
---
# Creating objects
```ruby
car = Car.new
car.class # => Car
car.is_a? Car # => true
Car.ancestors
# => [Car, Object, Kernel, BasicObject]
```
???
откуда у экземпляра пустого класса появились методы?
___
даже пустой класс наследуется от базовых классов которые предоставляют базовые методы
---
# Defining methods
```ruby
class Car
def accelerate!
@moving = true
end
def stop!
@moving = false
end
def moving?
@moving
end
end
```
---
# Defining methods
```ruby
car = Car.new # => #<Car:0x00000002033700>
car.moving? # => nil
car.accelerate! # => true
car.moving? # => true
car.stop! # => false
car.moving? # => false
car.inspect
# => "#<Car:0x00000002033700 @moving=false>"
```
???
inspect - один из стандартных методов (строкое представление обьекта)
___
показывает состояние обьекта
---
# Initializers
```ruby
class Car
def initialize(type)
@type = type
end
def big?
@type == 'big'
end
end
car = Car.new('big')
car.big? # => true
```
???
почему мы вызываем new, а определяем initialize?
---
# Attributes
```ruby
class Snake
def length
@meters * 100
end
def length=(santimeters)
@meters = santimeters / 100.0
end
end
snake = Snake.new
snake.length = 150 # => 150
snake.length # => 150.0
snake.inspect
#=> "#<Snake:0x00000002777930 @meters=1.5>"
```
---
# Attributes
## attr_accessor
```ruby
class Snake
def length
@length
end
def length=(new_value)
@length = new_value
end
end
class Snake
attr_accessor :length
end
```
---
# Attributes
## attr_reader
```ruby
class Snake
def length
@length
end
end
class Snake
attr_reader :length
end
```
---
# Attributes
## attr_writer
```ruby
class Snake
def length=(new_value)
@length = new_value
end
end
class Snake
attr_writer :length
end
```
---
# Attributes
## drawing the line
```ruby
class Snake
def length # attr_reader, attr_accessor
@length
end
def length=(new_value) # attr_writer, attr_accessor
@length = new_value
end
end
```
---
# Defining operators
```ruby
class Snake
attr_reader :length
def initialize(length)
@length = length
end
def +(other)
Snake.new(length + other.length)
end
end
```
```ruby
snake_1 = Snake.new(1) # => #<Snake:0x00000002f7d878 @length=1>
snake_2 = Snake.new(2) # => #<Snake:0x00000002f09fe0 @length=2>
snake_3 = snake_1 + snake_2
# => #<Snake:0x00000002eb3050 @length=3>
```
???
Было бы неплохо еще проверить класс
---
# Comparation
```ruby
class Snake
attr_reader :length
def initialize(length)
@length = length
end
end
snake = Snake.new(1) # => #<Snake:0x000000020800c8 @length=1>
other_snake = Snake.new(1) # => #<Snake:0x00000001e80ae8 @length=1>
snake == other_snake # => false
```
???
айдишник же разный вот и разные обьeкты
___
цифры тоже обьекты.. как они сравниваются?
___
показать object_id цифр
---
# Comparation
```ruby
class Snake
attr_reader :length
def initialize(length)
@length = length
end
def ==(other)
if other.is_a? Snake
length == other.length
else
false
end
end
end
snake = Snake.new(1)
other_snake = Snake.new(1)
snake == other_snake # => true
```
---
# Self
```ruby
class Snake
attr_reader :length
def initialize
@length = 1
end
def snake
self
end
def length_redefign
length # => 1
length = 5
length # => 5
self.length # => 1
end
end
```
???
просто аналог this
---
# Class methods
```ruby
class Snake
def self.description
'SNAAAAKESSS'
end
end
class Snake
class << self
def normal_description
'Snakes are elongated, legless, carnivorous reptiles of the suborder Serpentes' \
'that can be distinguished from legless lizards by their lack of eyelids and external ears.'
end
end
end
Snake.description # => 'SNAAAAKESSS'
Snake.normal_description # => 'Snakes ...'
```
???
просто разный синтаксис. self тут Snake
___
но если что class << пишет в синглтон класс класса (слайд с рисуночком)
---
# Class variables
```ruby
class Snake
@@count = 0
def initialize
@@count += 1
end
def all_count
@@count
end
end
Snake.new.all_count # => 1
Snake.new.all_count # => 2
```
???
статическая переменная и инстансы имеют к ней доступ
---
# Class instance variables
```ruby
class Snake
@count = 0
def self.add
@count += 1
end
def initialize
self.class.add
end
def all_count
@count
end
def self.count
@count
end
end
snake = Snake.new
# Oops..
snake.all_count # => nil
Snake.count # => 1
```
???
а это переменная имено класса как обьекта. она его. и инстансы ее не видят
---
# Class constants
```ruby
class Snake
NORMAL_LENGTH = 2
end
Snake::NORMAL_LENGTH # => 2
Snake::NORMAL_COLOR = '#6B554A'
Snake::NORMAL_COLOR # => '#6B554A'
Snake::NORMAL_COLOR = '#2D2D2D' # => warning: already initialized constant Snake::NORMAL_COLOR
Snake::NORMAL_COLOR # => '#2D2D2D'
```
---
# Visibility private
```ruby
class Snake
attr_reader :length
private
def initialize
set_defaults
end
def set_defaults
@length = 2
end
end
snake = Snake.new
snake.length # => 2
snake.set_defaults
# NoMethodError: private method `set_defaults'
# called for #<Snake:0x00000001d29b90 @length=2>
```
???
ну да initialize приватный.. он же вызывается другим методом так что всё ок
---
# Visibility protected
```ruby
class Snake
def +(other)
Snake.new(length + other.length)
end
private
def initialize(length)
@length = length
end
protected
attr_reader :length
end
```
---
# Protected example
```ruby
snake1 = Snake.new(1)
snake2 = Snake.new(2)
snake1 + snake2 # => #<Snake:0x00000001e82d70 @length=3>
snake1.length
# NoMethodError: protected method `length'
# called for #<Snake:0x00000001f95028 @length=1>
```
---
# Inheritance
```ruby
class Snake
attr_reader :length
def initialize(length)
@length = length
end
end
class LazySnake < Snake
def initialize(length)
@sleeping = false
super
end
def toggle_sleep
@sleeping = !@sleeping
end
def sleeping?
@sleeping
end
end
```
???
множественого наследования нет
___
есть миксины
---
# Inheritance example
```ruby
lazy = LazySnake.new(2)
lazy.length # => 2
lazy.sleeping? # => false
lazy.toggle_sleep
lazy.sleeping? # => true
```
---
# Inheritance
## super
```ruby
class LazySnake < Snake
def initialize(length)
super(length + 1)
end
end
lazy = LazySnake.new(2)
lazy.length # => 3
```
???
по умалчанию супер свхатит теже аргументы что и метод где он дергается
___
но можно указать другие аргументы
---
# Inheritance
## class variables
```ruby
class A
@@value = 1
def self.value
@@value
end
end
A.value # => 1
class B < A
@@value = 2
end
class C < A
@@value = 3
end
B.value # => 3
```
???
расшареная
---
# Inheritance
## constants
```ruby
class A
NUM = 2
end
class B < A
end
A::NUM # => 2
B::NUM # => 2
B::NUM = 3
A::NUM # => 2
B::NUM # => 3
```
???
а константы везде свои
---
# Singleton methods
```ruby
class Snake
def Snake.count
end
end
class Snake
class << self
def count
end
end
end
class << Snake
def count
end
end
```
???
same and eigenclass
---
# Custom behaviour of instance
```ruby
snake = Snake.new
def snake.name
"John"
end
snake.name # => John
class << snake
def name
"David"
end
end
snake.name # => David
another = Snake.new
another.name # => NoMethodError: undefined method 'name'
```
???
class << snake - это запись в eigenclass
___
обьекты в руби не хранят методы, методы хранятся в другом месте
___
обьекты хранят состояние. inspect тому пример
---
# Module
```ruby
module Speaking
def hi
puts 'HI!!!'
end
end
class Snake
include Speaking
end
snake = Snake.new
snake.hi
# 'HI!!!!'
```
???
комната в которой куча хлама
___
разкладываем хлам по коробочкам (модулям)
---
# Module constants
```ruby
module M
class C
X = 'a constant'
end
C::X # => "a constant"
end
M::C::X # => "a constant"
module M
Y = 'another constant'
class C
::M::Y # => "another constant"
end
end
M.constants # => [:C, :Y]
```
---
class: small
# Constants lookup order
```ruby
module Kernel
A = B = C = D = E = F = "from kernel"
end
A = B = C = D = E = "from toplevel"
class Super
A = B = C = D = "from superclass"
end
module Included
A = B = C = "from included module"
end
module Enclosing
A = B = "from enclosing module"
class Local < Super
include Included
A = "defined locally"
puts A # "defined locally"
puts B # "from enclosing module"
puts C # "from included module"
puts D # "from superclass"
puts E # "from toplevel"
puts F # "from kernel"
end
end
```
---
# Include and extend
```ruby
module A
def a
puts 'a'
end
end
module B
def b
puts 'b'
end
end
```
???
два простых модуля для обьяснения
___
и вобще в модули можно всунуть все что угодно
---
# Include and extend
```ruby
class Test
include A
extend B
end
test = Test.new
test.a # 'a'
test.b # NoMethodError
Test.b # 'b'
test.extend(B)
test.b # 'b'
```
???
include -добавляет содержимое модуля для инстансов которые будут сделаны
___
exntend - добавляет содержимое для текущего обьекта
---
# Include and extend and method lookup

---
# Exceptions
```ruby
begin
puts 'I am before the raise.'
raise 'An error has occured.'
puts 'I am after the raise.'
rescue
puts 'I am rescued.'
end
puts 'I am after the begin block.'
```
```
I am before the raise.
I am rescued.
I am after the begin block.
```
---
# Exceptions ensure
```ruby
begin
raise "A test exception."
rescue Exception => e
puts e.message
puts e.backtrace.inspect
ensure
puts "Ensuring execution"
end
A test exception.
# ["test.rb:2:in '<main>'"]
# Ensuring execution
```
???
ensure - всегда вызывается
___
пример - закрыть файл
---
# Exceptions else
```ruby
begin
puts "A test exception."
rescue Exception => e
puts e.message
puts e.backtrace.inspect
else
puts "Executes if there is no exception"
ensure
puts "Ensuring execution"
end
# A test exception.
# Executes if there is no exception
# Ensuring execution
```
???
else - если нет исключения
___
пример - вывод радосного сообщения
---
# Throw and catch
```ruby
def try(number)
throw :two! if number == 2
puts number
end
catch :two! do
try(1)
try(2)
try(3)
end
try(4)
# 1
# 4
```
???
вылезти из глубокой вложености
</textarea>
<script src="js/remark-0.5.9.min.js" type="text/javascript">
</script>
<script type="text/javascript">
var slideshow = remark.create();
</script>
</body>
</html>