Вы находитесь на странице: 1из 287

c

Ruby
Ruby 2.0.0p247


PDF :
http://dl.dropbox.com/u/75172405/Ruby.pdf
:
1. Ruby.
2. - gem

install redcarpet.

3. Markdown LaTeX
http://gist.github.com/Krugloff/5491182.
4. XeLaTeX.
5. - http://gist.github.com/Krugloff/5491168.
6. pdf - xelatex
Liberation).

book.tex

( -

:
: http://github.com/Krugloff
: mr.krugloff@gmail.com
:
Qiwi: 89212870782
WebMoney: R349517838989

I.

1.
1.1. . .
1.2. . . . . . .
1.3. . . .
1.3.1.
1.3.2. . . . . .
1.4. . . . .
1.5. . .

.
.
.
.
.
.
.

2
2
3
4
5
6
7
9

.
.
.
.
.
.
.
.
.
.

13
13
13
14
16
16
17
17
17
18
19

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

2.
2.1. . . . . . . . .
2.1.1. (Numeric) . . . . . . . . .
2.1.2. (String) . . . . . . . . . . .
2.1.3. . . . . . .
2.1.4. (Symbol) . . .
2.1.5. (Regexp)
2.2. . . . . . . .
2.2.1. (Array) . .
2.2.2. (Hash)
2.2.3. (Range) . . . . . . .

.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

3.
4.
4.1. . . . . . . . . . . . . . .
4.2. . . . . . . . . . . . .
4.2.1. . . . .
4.2.2. . . . .
4.2.3. . . . . . . . . . . . . . .
4.2.4. . . . . . .
4.2.5.
4.3. . . . . . . . . . . . . . . .

20

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

23
23
30
30
31
32
33
33
33

iii

5.
5.1. . . . . . .
5.1.1. (Module) . . . . .
5.1.2. (Class) . . . . . . .
5.1.3. . . . . . . . . .
5.1.4. . . . . . . . .
5.1.5. . . . . . . . . . . .
5.1.6. . . . . . . . . . .
5.2. . . . . . .
5.2.1. . . . . . . .
5.2.2.
5.2.3. . . . . . . .

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

35
35
35
36
38
38
39
46
48
48
50
53

II.

55

6.
6.1. Numeric . . . . . . . . . . . . . . .
6.1.1. . . . . . . .
6.1.2. . . . . . . . . . . .
6.1.3. . . . . . . . . . . .
6.1.4. . .
6.1.5. . . . . . . . . . . .
6.1.6. . . . . . . . . . . .
6.1.7. . . . . . . . . . . .
6.2. (Integer) . . . . . . . .
6.2.1. . . . . . . .
6.2.2. : Fixnum Bignum
6.2.3. . .
6.2.4. . . . . . . . . . . .
6.2.5. . . . . . . . . . . .
6.2.6. . . . . . . . . . . .
6.3. (Float) . . . . .
6.3.1. . . . . . . .
6.3.2. . . . . . . . . . . .
6.3.3. . . . . . . . . . . .
6.3.4. . . . . . . . . . . .
6.4. (Rational) . .
6.4.1. . . . . . . .
6.4.2. . . . . . . . . . . .
6.4.3. . . . . . . . . . . .
6.5. (Complex) . . .
6.5.1. . . . . . . .
6.5.2. . . . . . . . . . . .
6.5.3. . .
6.6. Math . . . . . . . . . . . . . . . . .

56
56
56
57
58
58
60
60
60
60
61
61
62
62
63
63
63
64
64
65
65
65
65
66
66
66
67
68
68
69

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

iv

7.
7.1. (String) . . . . . . . . . . . . . . . . . . . . . . .
7.1.1. . . . . . . . . . . . . . . . . . .
7.1.2. . . . . . . . . . . . . . . . . . . . . . .
7.1.3. . . . . . . . . . . . . . . . . . . . . . .
7.1.4. . . . . . . . . . . . . . . . . . .
7.1.5. . . . . . . . . . . . . . . . . . .
7.1.6. . . . . . . . . . . . . . . . . . . . . . .
7.1.7. . . . . . . . . . . . . . . . . . . . . . .
7.1.8. . . . . . . . . . . . . . . . .
7.1.9. . . . . . . . . . . . . . . . . . . . . . .
7.2. . . . . . . . . . . . . . . . . . .
7.2.1. Regexp . . . . . . . . . . . . . . . . . . . . . . . .
7.2.2. MatchData . . . . . . . . . . . . . . . . . . . . . .
7.3. . . . . . . . . . . . . . . . . . . . . . . . . .
7.3.1. (Encoding) . . . . . . . . . . . .
7.3.2. (Encoding::Converter)
8.
8.1. Array ( ) . .
8.1.1. . . . . .
8.1.2. . . . . . . . . .
8.1.3. . . . . . . . . .
8.1.4. . . .
8.1.5. . . . .
8.1.6. . . . . . . . . .
8.1.7. .
8.1.8. . . . . . . . . .
8.2. Hash ( )
8.2.1. . . . . .
8.2.2. . . . . . . . . .
8.2.3. . . . .
8.2.4. . . . . . . . . .
8.2.5. . . . . . . . . .
8.2.6. . . . .
8.2.7. . . . . . . . . .
8.3. Range () . . . . . . .
8.3.1. . . . . .
8.3.2. . . . . . . . . .
8.3.3. . . . . . . . . .
8.3.4. . . . . . . . . .
8.3.5. . . . . . . . . .
8.4. Enumerator () . . . . . .
8.4.1. . . . . .
8.4.2. . . . . .
8.4.3. . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

72
72
72
75
79
79
83
86
86
87
87
88
88
90
92
92
93

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

98
98
98
99
102
103
106
107
108
108
110
110
111
112
113
114
114
114
115
116
116
116
116
117
118
119
119
120

8.4.4. . . . . . . . . . . . . . . . . . . .
8.4.5. (Enumerator::Lazy)
8.5. Enumerable . . . . . . . . . . . . . . . . . . . . .
8.5.1. . . . . . . . . . . . . . . .
8.5.2. . . . . . . . . . . . . . . . . . . .
8.5.3. . . . . . . . . . .
8.5.4. . . . . . . . . . . . . . . . .
8.5.5. . . . . . . . . . . . . .
8.5.6. . . . . . . . . . . . . . . . . . . .
8.5.7. . . . . . . . . . . . . . . . . . . .
8.5.8. . . . . . . . . . . . . . . . . . . . . .
8.5.9. . . . . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

120
120
122
123
123
123
124
125
126
126
127
128

9.
9.1. . . . . . . . . . . . . . .
9.1.1. . . . . . . .
9.1.2. . . . . . . . . . . . .
9.1.3. . . . . . .
9.1.4. . . . . . . . .
9.1.5. . . . . . . . .
9.2. . . . . . . . .
9.2.1. .
9.2.2. . . . . . . . . . . .
9.2.3. . . . . . . .
9.2.4. . . . . . . .
9.2.5. . . . . . . .
9.3. . . . . . . . . . . . . . . . .
9.3.1. . . . . . . . . .
9.3.2. . . . . . . . .
9.3.3. . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

129
129
129
130
131
132
133
135
135
136
136
138
138
140
140
141
141

10.
10.1. (Proc) . . . . . . . .
10.1.1. . . . . . . . .
10.1.2. - . . . . .
10.1.3.
10.2. . . . . . . . . . . . . .
10.2.1. Method . . . . . . . . . . .
10.2.2. UnboundMethod . . . . . .
10.3. (Fiber) . . . . .

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

145
145
146
146
147
149
149
151
152

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

11. (Random)
154
11.1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155

vi

12.
12.1. (Time) . . . . . .
12.1.1. .
12.1.2.
12.1.3. . . . . .
12.1.4. .
12.1.5. .
12.1.6. . . . .
12.1.7. . . . . .
12.1.8. . . . . .

.
.
.
.
.
.
.
.
.

13.
13.1. . .
13.2. Symbol . . . . . . . . . .
13.2.1. .
13.2.2. . . . . . .
13.2.3.
13.2.4. . . . . . .
13.3. . . . . . . . .
13.3.1. .
13.3.2. . . . . . .
13.3.3. . . . . . .
13.3.4. . . . . . .

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

156
156
156
157
158
158
158
159
160
161

.
.
.
.
.
.
.
.
.
.
.

162
162
162
162
163
163
163
164
164
165
165
165

III.
14.
14.1. . . . . . .
14.2. . . . . . . .
14.3. . .
14.4. . .

167
.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

168
168
168
169
169

15.
15.1. IO () . . . . . . . . . . . . . . . . . .
15.1.1. . . . . . . . . .
15.1.2. . . . . . . . . . . .
15.1.3. . . . . . . . . . . . . .
15.1.4. . . . . . . . . . . . . .
15.1.5. . . . . . . . . . .
15.1.6. . . . . . . . . . . . . . . . .
15.1.7. . . . . . . . . .
15.2. File () . . . . . . . . . . . . . . . . .
15.2.1.
15.2.2. . . . . . . . . . . . . . .
15.2.3. . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

171
171
171
174
175
178
180
181
182
183
184
185
188

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

vii

15.2.4. . . . . . . . . .
15.2.5. . . . . . . . . . .
15.3. Dir () . . . . . . . . . . .
15.3.1.
15.3.2. . . .
15.3.3. . . . . . . . . . .
15.3.4. . . . . . . . . . .
15.4. . . . . . .
15.4.1. File::Stat . . . . . . .
15.4.2. FileTest . . . . . . .

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

189
190
191
192
192
193
193
193
194
197

16.
199
16.1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
16.1.1. ARGV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
16.1.2. ARGF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
17.
203
17.1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
17.2. (Ruby 2.0) . . . . . . . . . . . . . . . . . . . 204
18.
18.1. . . . . . . . . . . .
18.2. . . . . . . . . . . . . . . . . . . .
18.2.1. Exception . . . . . . . . . . . . . . .
18.2.2. LoadError [ruby 2.0] . . . . . . . . . .
18.2.3. SignalException . . . . . . . . . . . .
18.2.4. SystemExit . . . . . . . . . . . . . . .
18.2.5. Encoding::InvalidByteSequenceError .
18.2.6. Encoding::UndefinedConversionError
18.2.7. StopIteration . . . . . . . . . . . . . .
18.2.8. LocalJumpError . . . . . . . . . . . .
18.2.9. NameError . . . . . . . . . . . . . . .
18.2.10. NoMethodError . . . . . . . . . . . .
18.2.11. SystemCallError . . . . . . . . . . .
18.3.
18.3.1. . . . . . . . . . .
18.3.2. . . . . . . . .
18.3.3. Catch Throw . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

209
209
210
210
211
211
211
212
212
212
213
213
213
213
213
213
214
215

19.
19.1. . . . . . . . .
19.1.1. . . . . . . . .
19.1.2. TDD . . . . . . . . . .
19.2. . . . . . . . . . . .
19.2.1.
19.2.2. . . .

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

216
216
216
217
217
217
218

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

viii

19.2.3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
20.
20.1. . . . . . . . . . . . . . . . . . . .
20.1.1. . . . . . . . . . . . . .
20.1.2. . . . . . . . . . . . . .
20.1.3. . . . . . . . . . . .
20.1.4. . . . . .
20.2. (Thread) . . . . . . .
20.2.1. Thread . . . . . . . . . . . . . . . . .
20.2.2. (ThreadGroup)
20.2.3. (Mutex) . .
20.3. (Process) . . . . . . . . . . . .
20.3.1. Linux . . . . . . . . . . . . . . . . . .
20.3.2. . . . . . . . . .
20.3.3. Ruby . . . . . . . . . . . . . . . . . .
20.4. (Signal) . . . . . . .
20.5. . . . . . . . . . . . .
20.6. C . . . . . . . . . . . . . . . .
20.6.1. Ruby 2.0 . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

224
224
224
225
225
226
226
227
234
235
236
236
237
237
238
239
240
240

21.
21.1.
21.1.1. 0 . . . .
21.1.2. 1 . . . .
21.1.3. 2 . . . .
21.1.4. 3 . . . .
21.1.5. 4 . . . .
21.2. . . . .

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

242
242
242
242
243
243
243
244

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

245

A.

246

B.

250

C.

256

D.

259

E.

262

F.

263

G.

265

ix

H.
I. Linux
I.1. . . . . . . . . . . . .
I.2. . . . . . . . . . . . .
I.3. . . . . . . . . . .
I.4. . . . . . . . . . .

270

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

272
272
273
274
276

277


- ,
. , .

1.1.
-
- ,
, .
W. A. Wulf
24 1993 . (Matz) . Ruby.
, Perl,
Python. .
Ruby
, , ,
.
Ruby:
,
. , ;
( );
. .
,
.
. , Ruby - .
. API - .

1.2.

Ruby:
;
-;
;
;
, (DSL);
;
;
;
;
Unicode;
, ;
, , .

1.2.
- , , .

:
MRI - , YARV ( , ,
).
Rubinius - . C++, Ruby;
JRuby - Java;
IronRuby - .Net.
. , .
Windows
.
:
( );

1.3.

RubyGems;
irb ( Ruby
);
RDoc;
ri ;
Rake;
ERb.

1.3.
Ruby - ,
( - ,
).
Ruby : .rb ( )
.rbw ( Windows ).
,
. .
.
- , . , ,
.
:
- (, , );
- , :
.
. -
, (_).
.
.
ASCII (
ASCII ,
).
, ;
- , , ;

1.3.

- , . , .
.
: __LINE__; __ENCODING__; __FILE__; __END__; BEGIN;
END; =begin; =end; alias; and; begin; break; case; class; def; defined?; do; else;
elsif; end; ensure; false; for; if; in; module; next; nil; not; or; redo; rescue; retry;
return; self; super; then; true; undef; unless; until; when; while; yield;
- ,
.
. - , . ( ), ( , ).
.
, . , .
,
.

1.3.1.
Ruby ( ) , , .
.

.
:
. 80
( );
( );
, .
.

1.3.

:
( , , ENTER);

(;);
, , , (backslash - \), (
). , ,
- ;
, (.), ;
(, , ),
,
. - .

1.3.2.
- ,
.
( ) .
- . , .
,
.
,
. .
, .

.
Ruby :
, , .
# .
# .

1.4.

=begin =end . .
=begin .
.
,

.
=end

1.4.
, ,
, - .
. . . ff 255
11111111 .
,
. (code point) .
,
.
- ( ). 10000 (32
, 20 ). .
.

ASCII, 127 : , , . 127
7 , ASCII , .
.
255 . 128 ( 128 255)
: .
hello 48 65 6c 6 6a.
.

.
,
. :
.

1.4.

(Unicode).
, .
, . , ( ),
-.
U+xxxx, x ( ). , .
100 . .
, hello : U+0048 U+0065
U+006C U+006C U+006F.
- . hello
00 48 00 65 00 6 00 6 00 6,
48 00 65 00 6 00 6 00 6 00. ,
.
- UTF-8.
ASCII - , ASCII
( hello UTF-8 ASCII).
. , , ASCII
.
,
. . , ASCII ( Ruby - UTF-8,
).
, ASCII.
( ) , ASCII ( ),
.
, ASCII,
.
, : #coding: _
:
coding encoding;
;
;
;
coding -*-.

1.5.

1.5.
- ,
.
, , .
- () - , .
Smalltalk, Ruby. , , .
, ,
.
.
, , .
,
( ) .
- ,
. ,
. , Ruby , - -
- .
- , , , , , , .
- - ,
() ,
- . ,
.
:
- . , - .
- , ,
. - , .
, ,
( ). - .

1.5.

10

:
- () ( ),
.
( ).
, .
, .
, (
- ).
, .
- .
, ( ).
, .
:
. - .
, .
.
( ).
. -
, . , , , . ,
.
, ,
.
,
.
:
- ,
.
, .
,
.
,
;

1.5.

11

,
;
, , . , .
:
- ,
, ( ). ,
() , , () - . .
;
,
.
, ;
,
. (
).
:
- , .
, ;
, ;

.
:
- , , , , .
Ruby .
(

1.5.

12


).
()
.
.
() ( )
, . , .
Ruby ,
. , . ,
, .


. -
.

2.1.
, , , . -
. .

2.1.1. (Numeric)
(Integer)
, 31- ,
Fixnum.
, , Bignum.
.
- (1289).
(_), .
(1_000_000 - ).
:
, .
;
, 0x 0X, (04AF);
, 0b 0B,
(0b0111).
(-).
(+). .

2.1.

14

(Float)
- ,
: (123.051).
.
(e ), , 10 (123-10 - 123 1010 ).
(_), .

2.1.2. (String)
- . - .
. ,
,
.
(line), (string)
. , .
: ,
('Ruby').
, .
( ).
- , , .

:
\ - ;
\ - .
: ,
("Ruby").

.
- "#{}"
("#{1+2}" - 3).

.

2.1.

15

:
\* - *, . .
-
;
\b - ;
\r - . ( ).
.
(
).
\n - ( ). Windows
\r\n.
\t - , ();
\*** - ,
;
\** - \0**;
\* - \00*;
\x** - , ;
\x* - \x0*;
\u**** - ,
;
\u{*} ,
.
: %q %Q.
%q %Q. , .
%q , %Q (%Q(Ruby) - Ruby). %Q
(%(Ruby)).
: , .
<< <<-.
, .
() . ,
. ,
.

2.1.

16

<<, .
;
, . .
( ).
<<- 'DOC'
.
DOC
# -> ' '

: , ?.
, (?A
A).

2.1.3.
, .

:
: true, TrueClass;
: false, FalseClass;
: nil, NilClass. , , .
false nil false, - true.
( true)
( false).

2.1.4. (Symbol)
. -
.
Symbol.

2.2.

17

- - , (:green). , %s
(%s(Ruby) - :Ruby)
, , ,
. , , . .
- , ( ). , .

2.1.5. (Regexp)
- . , .
- (
), (slash - /).
,
(/Ruby/i).
%r.
(%r(Ruby)i
/Ruby/i).
. , . ,
.
.

2.2.
- , ( ).
.

2.2.1. (Array)
( ) - ,
,

2.2.

18

( ).
( ).
, -
. .
[1, "Ruby", ?\u0048]

, (
).
%w %W. .
%w
, %W - .
%W( Ruby ) :
[ "", "", "Ruby" ]

Ruby ,
-.
%i %I.
.
%i
, %I - .
%I( category klass ) :
[:category, :klass]

2.2.2. (Hash)
- ,
( /)
, ( ).

.
, , ( ),
.hash. ,
.
( ).
, - / .
=>. .
{ "Ruby" => "language", "" => "" }

- . -

2.2.

19

,
( ).
{ Ruby: "language", : "" }

:
{ :Ruby => "language",

: => "" }

2.2.3. (Range)
- ,
, .
, - , .
(1..3 1, 2, 3),
- (1...3 1 2).
.
<=>, , , .


- , . , . , , . , , .
. ,
( ).
() .
,
.
. . . ,
.
, Ruby,
. .
.
. .
() () .
. . ( nil). ,
, .
, .

, ( nil).
- .
, ,
.

3.

21

_. Ruby , .
:
, .
. . .
( ). .
, .
( ,
- _). ;
. ;
(
, - __). (
).
:
. .
@ ( ). ;
@@ ( ). .
:
Ruby , , .
.
,
. .

3.

22

- .
,
. , ,
. ,
, ,
( ).
,
.

- , (
) . . .
( ).
.

4.1.
-
. - . .
, , , .
:
() - ;
() - ;
() - .
.
, ,
.
( ), , . R- ,
L- - .
, , , .

4.1.

.
1

!~ +

.
R

2
3
4

**
* / %

R
R
L

+-

<< >>

7
8

&
| ^

L
L

9
10
10

< <= > >=


<=> ! = =~
!~ == ===

L
L
L

11
12
13
14
15
16

&&
||
?:
=
not
and or

L
L
R
R
R
L

24


;
;



(); ;
()
();
()
()

( )
( );

; ;
; ;



4.1.

25

1. !obj ( )
.
!1 # -> false
!nil # -> true

~ integer ( )
1.
, .
-number-1.
~1 # -> -2
~0b01 # -> -2

+ number ( )
.
+0b01 # -> 1

2. number**number ( )
. -
, - .
2**3 # -> 8

3. - number ( )
, .
-0b01 # -> -1

4. number * number ()
.
1 * 2 # -> 2

string * integer ( )
.
"R" * 3 # -> "RRR"

array * integer ( )
.
[1, ?R] * 2 # -> [1, "R", 1, "R"]

[*object] ( )
.

4.1.

26

a = [1, 2, 3]
[*a] # -> [1, 2, 3]
[*a, 1] # -> [1, 2, 3, 1]
b = { a: 1, b: 2 }
[*b] # -> [ [:a, 1], [:b, 2] ]
c = 1..4
[*c] # -> [1, 2, 3, 4]
[*1] # -> [1]
[*nil] # -> [ ]
[*?a] # -> ["a"]

number / number ()
.
-6 / 3 # -> -2

number % number ( )
. .
7 % 3 # -> 1
-7 % 3 # -> 2
7 % -3 # -> -2

string % object ()
,
. ,
, .
5. number + number ()
.
1 + 3 # -> 4

string + string ( )
.
"Ruby" + ?! # -> "Ruby!"

array + array ( )
.
[1, 2] + [3, 4] # -> [1, 2, 3, 4]

number - number ()
.
2 - 1 # -> 1

array - array ( )
.
[1, 2, 2, ?R] - [2, ?1] # -> [1, "R"]

4.1.

27

6. number integer; number integer ( )


.
1 << 2 # -> 4

string string ( )
.
, .
"Ruby" << ?! # -> "Ruby!"
"Ruby" << 33 # -> "Ruby!"

array object ( )
.
[1] << 2 # -> [ 1, 2 ]

7. integer & integer ( )


.
1,
1.
0b01 & 0b10 # -> 0

array & array ( )


, .
[1, 2, 2, 3] & [2, 3] # -> [2, 3]

8. integer | integer ( )
.
1, 1.
0b01 | 0b10 # -> 3

array | array ( )
,
.
[1, 2, 2, 3] | [2, 3] # -> [1, 2, 3]

integer ^ integer ( )
.
( )
1, 1.
0b01 ^ 0b10 # -> 3

9. < <= >= > ()


.
:

4.1.

28

1 <= 2 # -> true


1 > 2 # -> false

:
.
.
, .
, .
"" < "" # -> true
"" < "" # -> false
"1" <= "2" # -> true

10. object == object ()


. ,
.
1 == 1.0 # -> true
1 == "1" # -> false

object != object ()
.
1 != 1.0 # -> false
1 != "1" # -> true

object === object ( )


.
.
1 === 1.0 # -> true
1 === "1" # -> false
String

=== 'matz' # -> true

Numeric === 42

# -> true

string =~ regexp; regexp =~ string ( )


.
, ,
nil, .
string !~ regexp; regexp !~ string ( )
.
object <=> object ()
.

4.1.

29

< = >
# ->

-1 0 1

-1 ;
0 ;
1 ;
nil ( ).
, , (
).
1 <=> 1.0 # -> 0
1 <=> ?2 # -> nil

11. expression && expression ( )


.
4 && 2 - 1 # -> 1
3 > 4 && 2 - 1 # -> false

12. expression || expression ( )


.
4 || 2 - 1 # -> 4
3 > 4 || 2 - 1 # -> 1

13. expression ? expression : expression ( )



( ) (
)
1 > 2 ? true : false # -> false
1 < 2 ? true : false # -> true

14. identificator = object ()


.
**= *= /= %= += -= = = &&= &= ||= |= ~= ()
- ,
.
<1> op= <2> <1> = <1> op <2>
15. not object ( )
!object, .
16. expression and expression ( )
expression

&& expression,

experssion or expression ( )
expression

|| expression,

4.2.

30

4.2.
- , ( ). , end,
. , , .

4.2.1.
.
( nil).
:

.
if
_
end

,
, then.
else:
, .
...
_
else

end

else elsif.
:
_ if

,
begin end, .

4.2.

31

begin
_
end if

( _
) if

if unless, .
elsif .

4.2.2.
, . . -
. ( nil).
:
.
case
when

when

...
end

, .
.
:
( ===).
case
when

when

...
end

else.

4.2.

32

4.2.3.
- ( ). , . nil.
while .
, .
:
( ).
while
_
end

,
, do.
:
_ while

.
begin end, .
.
begin
_
end while

( _
) while

while until,
.
until while not.

Kernel - .loop { }, StopIteration
. while true.

4.3.

33

4.2.4.
- ,
.
for in
_
end

(
, ).
.each, .
,
, do.

4.2.5.

. , . , nil.

:
return [] -
, , ;
break [] - ;
next [] -
;
redo - .
.

4.3.
. - , .. ....
, ,
( 12.5).
.
, .
,
, .. .

4.3.

34

.
:
..; ...

- , , .
,
.
.
. . , .
:
1. , .
. ..
.
2. , . , .
.

. ...
, .. - .


Ruby -
- .
, , .
.

.
:
;
( )
,
. .
- , ,
;
, ;
, ;
- . ;
,
. .

5.1.
5.1.1. (Module)
- , , .

5.1.

36

.
.
. , ..
.
Math, .
- , . ,
, -
.
,
- .
module _
_
end

module , .
, . ;
. . self
.
( nil).
Module. ,
, .
::new { nil } # -> module [Module]
. . ,
.

5.1.2. (Class)
- , , . , - .
( ) .

5.1.

37

class _
_
end

class ,
. ,
. .
. .
self . ( nil).
Class. ,
, .
::new( class = Object ) # -> class [Class]
, .
, .
: , .
, , .
Ruby ::new.
: (
.allocate) ( .initialize).
.initialize . .
.
.allocate Class
.
: .
, ,
. . (metaclass).
class <<
_
end


( ).
self.
( nil).
,
, .

5.1.

38

5.1.3.

, .
::, L.
, . .
::

=, .
, ,
.
.
self.
,
.
1. , ;
2. , ;
3. , ;
4. 1-3;
5. object.const_missing , .

5.1.4.
: .
: .
: , .
(
). @@.
(
).
.
, .
. .
: ,
.
.
@.

5.1.

39

. .

. . .
, ,
, . , Class.

5.1.5.
- , , , ,
(, ). : . Ruby
- .
, .
- , ( );
- , (
).
( ) , .
, - , . .
nil. , .
.

: , .
def _()
_
end

-
.
: , .

5.1.

40

def ._()
_
end

self.
, ,
- .
- ,
( ).
:
;
( )
( ).

.

:
:
.
:
;
, ;
( );
- , - . , . .
: , (, ).
.
.

5.1.

41

, . ,
. ,
, . , , ;
(*), , . ,
. ;
(&),
( .to_proc).
, yield.
, is.
: , .
. .
self , .
: , .
.
, .
alias: alias _

, : = .
: undef. ,
( ).
undef _

Ruby 2.0
. .
, Ruby.
- , .
, . .

5.1.

42

def method(name: default); name; end


method(name: 'method') # -> method

.
def method(name: default); name; end
method(args: 'method') # -> ArgumentError!

(**), , .
( **)
def method(**options); options; end
method(name: 'method') # -> { name: 'method'}

- Ruby, .
- .
.
, - ,
. ,
. .
, .
<method> { || _ }

<method> do ||
_
end

do
- , .
, , , .
, . . , .
, .
.
Ruby - ,
(for in).

5.1.

43

:
: , (, ).
.
.
. (
*).
: . , .
self ,
, .
- , . ,
(| x, y; z, k, n |).
nil.
: . .
yield, , ( ).
. .
yield LocalJumpError.
,
.
hash = { a: [], b: [] }
hash.each { |key, (first_in_value, second_in_value)| }

. ,
( nil).

:
return [] - ,
, ;
break [] - ;

5.1.

44

next [] - .
;
redo - .


. ( ::,
),
L.
, ( ),
- .
._()

- , .
.
. .
.
self.
.
- .
;
- ,
;
- , ,
, ,
. .
, Ruby
. ,
, , ,
.
:
(
, );

, ;

5.1.

45

(*). .to_splat;
,
(&).

. ( ).
;
;
, ;
2 3;
.method_missing.
Ruby 2.0

(**). .
APP_OPTS = { name: 'play', author: 'dave' }
LOG_OPTS = { level: 2, color: 'blue', line: '3pt' }
def log(msg, options)
p msg
p options
end
log( 'Starting', **APP_OPTS )
# ->
# 'Starting'
# { name: 'play', author: 'dave' }
log( 'Connected', **APP_OPTS, **LOG_OPTS )
# ->
# 'Connected'
# { name: 'play', author: 'dave',
#

level: 2, color: 'blue', line: '3pt' }

log( 'Giving up', **APP_OPTS, **LOG_OPTS, color: 'VERY RED' )


# ->
# 'Giving up'
# { name: 'play', author: 'dave',
#

level: 2, color: 'VERY RED', line: '3pt' }

5.1.

46


. ,
( nil).

:
return [] - ;
break [] - ;
next [] - ;
redo - .
: ,
.
( ), .
def .
_
end

(
). ,
.
nil.
. , , ( ).

5.1.6.
.
.to_s .

5.1.

module OurKlass
class User
@@count = 0 # class var.
# class method.
def self.count
@@count
end
def initialize( name, age )
@name = name # instance var.
@age = age
@@count += 1
@id += 1
end
# instance method.
def to_s
"#{@name}: #{@age} years old"
end
end # class User.
end # module.

. .to_a .
user = OurKlass::User.new "Timmy", 22 # -> "Timmy: 22 years old"
OurKlass::User.count # -> 1
user.to_a # -> error!

.to_a.
class OurKlass::User
def to_a
[ @name, @age ]
end
end
user.to_a # -> ["Timmy", 22]

47

5.2.

48

class OurKlass::User
def self.next_count
@@count + 1
end
end
OurKlass::User.next_count # -> 2
class OurKlass::User
class << self
def prepend_count
@@count - 1
end
end
end
OurKlass::User.prepend_count # -> 0

. .
class << user
def id
@id
end
end
user.id # -> 1
user = OurKlass::User.new "Tommy", 33 # -> "Tommy: 33 years old"
user.id # -> error!

5.2.
5.2.1.

.
, . ( ) ( ).
. ,
.

5.2.

49

, , .
(<attr>=).

Module.
.attr_accessor(*attribute) # -> nil
.
.attr_reader(*attribute) # -> nil
.
.attr_writer(*attribute) # -> nil
.


.
( ), ( ).
.
:
public - . . ;
protected - .
.
( )
( ) (
);
private - . .
( ) ( )
( self).
API.
,
- .

5.2.

50

Module: .public, .private .protected. , . , , Object.


.private_class_method(*name) # -> self [Module]
.
.
.public_class_method(*name) # -> self [Module]
.
.module_function(*name) # -> self [PRIVATE: Module]
. , .
, .

5.2.2.

Ruby
( ).
Ruby . ,
.

.
class _ < _

;
. , ;
.
;
. .

- ,
(
). , .
Ruby .

5.2.

51

Ruby . , .
.
.include(*a_module) # -> self [PRIVATE: Module]
.
.
.
.extend(*a_module) # -> object [Object]
.
. .
.extend_object(object) # -> object [PRIVATE]
.
object.extend self

extend self ,

.
Ruby 2.0
Ruby ,
.
.prepend(*a_module) # -> self [PRIVATE: Module]
.
. . , super.
module Foo
def baz; 'foo-baz'; end
end
class Bat
include Foo
def baz; 'bat-baz'; end
end
Bar.new.baz # -> 'bat-baz'
class Bar
prepend Foo
def baz; 'bar-baz'; end
end
Bar.new.baz # -> 'foo-baz'

5.2.

52

.
,
.
# Ruby 1.9:
class Range
# active_support/core_ext/range/include_range.rb
# Range#include? .
def include_with_range?(value)
if value.is_a?(::Range)
# 1...10 1..9, 1..10.
operator = exclude_end? && !value.exclude_end? ? :< : :<=
include_without_range?(value.first) && value.last.send(operator, last)
else
include_without_range?(value)
end
end
alias_method_chain :include?, :range
end
Range.ancestors # -> [ Range, Enumerable, Object... ]
# Ruby 2.0
module IncludeRangeExt
# Range#include? .
def include?(value)
if value.is_a?(::Range)
# 1...10 1..9, 1..10.
operator = exclude_end? && !value.exclude_end? ? :< : :<=
super(value.first) && value.last.send(operator, last)
else
super
end
end
end
class Range
prepend IncludeRangeExt
end
Range.ancestors # -> [ IncludeRangeExt, Range, Enumerable, Object... ]

5.2.

53


- , ( Ruby
).
BasicObject,
Object, .
Object Kernel,
.
Module,
Object. Module
.
Class,
Module. Class
.
Module .
Class .
.
;
;
;

5.2.3.
Ruby
.
: , ,
. Ruby . , -
.
, , .

super, (
).
: , , . Ruby
nil.

5.2.

54

: , .
. , -
.
Ruby , .
Numeric, -
, IO, , . .
: (), . , ,
. , , .
.
, .
module Openable
def open; end
def close; end
end


Ruby , .
- .
. , , .
<op> object <-> object.<op>
first_object <op> second_object <-> first_object.<op>(second_object)

, :
., ::, &&, ||, ?:, =, , not, and, or, .., ...

II

N umeric (+ Comparable)


Complex

TTTTXXXXZXZZZZZZ
TTTT XXXXXXZZZZZZZZ
TTTT XXXXXX ZZZZZZZZ
XXXXX
TTT*
XXXXXZZZZZZZZZZZZZ
+
,

Rational

F loat

IntegerM


MMM
MMM
MMM
M&

F ixnum

Bignum

Ruby Math.

6.1. Numeric
: Comparable
.
- , .

6.1.1.

. ,
.
:
1. - ,
;
2. - , ;
3. - , .
, .

6.1. Numeric

57


.coerce(number) # -> array
.
1. , .Float;
2. , (
).
1.coerce 2.1 # -> [2.1, 1.0]
1.coerce "2.1" # -> [2.1, 1.0]
1.coerce "0xAF" # -> [175.0, 1.0]
1.coerce "q123" # -> error!

.i # -> complex
. Complex.
1.i # -> (0+1i)

.to_c # -> complex


.
1.to_c # -> (1+0i)

.to_int # -> integer


number.to_i.
2.1.to_int # -> 2

6.1.2.
.%(number)
: modulo
.
.+(number)

.-(number)

.<=>(number) .

6.1. Numeric

58

6.1.3.
.ceil # -> integer
, ( ).
2.1.ceil # -> 3

.floor # -> integer


, ( ).
2.1.floor # -> 2

.round( precise = 0 ) # -> number


.
, .
2.11355.round 4 # -> 2.1136
2.round 4 # -> 2.0

.truncate # -> integer


.
2.1.truncate # -> 2

6.1.4.
.abs2 # -> number
.
-2.1.abs2 # -> 4.41

.numerator # -> integer


, number.to_r.
2.1.numerator # -> 4728779608739021

.denominator # -> integer


, number.to_r.
2.1.denominator # -> 2251799813685248

.divmod(number) # -> array


.
1.divmod 3 # -> [0, 1]

.div(number) # -> integer


( number.to_i).
1.div 3 # -> 0

.fdiv(number) # -> float


.
1.fdiv 3 # -> 0.3333333333333333

59

6.1. Numeric

.quo(number) # -> quotient


.
.
1.quo 3 # -> (1/3)

.remainder(number) # -> integer


,
self number * ( self / number ).truncate.
1.remainder 3 # -> 1

.abs # -> number


.
-2.1.abs # -> 2.1

.arg # -> number


: angle, phase
.
, .
Math::PI.
1.arg # -> 0
-1.arg # -> 3.141592653589793

.polar # -> array


([

self.abs, self.arg ]).

1.polar # -> [1, 0]

.real # -> number


.
1.real # -> 1

.imag # -> 0
: imaginary
.
.rect # -> array
([

self, 0 ]).

1.rect # -> [ 1, 0 ]

.conj # -> self


: conjugate
( ).

6.2. (Integer)

60

6.1.5.
.integer? # -> bool
.
1.integer? # -> true
2.1.integer? # -> false

.real? # -> bool


(
).
1.real? # -> true

.nonzero? # -> bool


. , .
1.nonzero? # -> 1
0.0.nonzero? # -> nil

.zero? # -> bool


.
1.zero? # -> false
0.0.zero? # -> true

6.1.6.
.step( limit, step = 1) { |number| } # -> self
.
, .
n + n * Flt::EPSILON, n == limit self / step.

6.1.7.
.singleton_method_added(*object)
.

6.2. (Integer)
.
Fixnum Bignum .

6.2. (Integer)

61

6.2.1.
.to_i # -> self
.to_r # -> rational
: rationalize
.
0.to_r # -> (0/1)

.to_f # -> float [Fixnum Bignum]


.
1.to_f # -> 1.0

.to_s( numeral_system = 10 ) # -> string [Fixnum Bignum]


, ( 2 36).
16.to_s 16 # -> "10"
0xF.to_s 16 # -> "f"
0x16.to_s 16 # -> "16"

6.2.2. : Fixnum Bignum


.*(integer) # -> result .
./(integer) # -> result .
.**(integer) # -> result .
.+(integer) # -> result .
.-(integer) # -> result .
.~(integer) # -> result .
.[](index) # -> 0 1

.
.(integer) # -> result .
.(integer) # -> result .
.&(integer) # -> result .
.|(integer) # -> result .
.^(integer) # -> result .

6.2. (Integer)

62

6.2.3.
.next # -> integer
: succ
.
1.next # -> 2

.pred # -> integer


.
1.pred # -> 0

.gcd(integer) # -> gcd


. ,
integer.abs .
2.gcd 3 # -> 1

.lcm(integer) # -> lcm


. , .
2.lcm 3 # -> 6

.gcdlcm(integer) # -> array


[

self.gcd(integer), self.lcm(integer) ]

2.gcdlcm 3 # -> [ 1, 6 ]

6.2.4.
.even? # -> bool
.
0.even? # -> true
1.even? # -> false
2.even? # -> true

.odd? # -> bool


.
0.odd? # -> false
1.odd? # -> true
2.odd? # -> false

6.3. (Float)

63

6.2.5.
.upto(limit) { |integer| } # -> self
() +1.
.downto(limit) { |integer| } # -> self
() -1.
.times { |integer| } # -> self
0...self.

6.2.6.
.chr( encode = binary) # -> string
. RangeError.
42.chr # -> "*"

.hash # -> integer [Fixnum Bignum]


.
1.hash # -> -861462684

.size # -> integer [Fixnum Bignum]


, .
1.size # -> 4

6.3. (Float)
Ruby .

:
Float::ROUNDS - ;
Float::RADIX - ;
Float::MANT_DIG - ;
Float::DIG - ;
Float::MIN_EXP - 10;
Float::MAX_EXP - ;
Float::MIN_10_EXP - ;
Float::MAX_10_EXP - ;
Float::MIN - ;
Float::MAX - ;
Float::EPSILON - , ,
1.0;

64

6.3. (Float)

Float::INFINITY - ;
Float::NAN -
0.0 / 0.0.

6.3.1.
.to_f # -> float
.to_i # -> integer
.
2.1.to_i # -> 2

.to_r # -> rational


.
2.1.to_r # -> ( 4728779608739021 / 2251799813685248 )

.rationalize( number = Flt::EPSILON ) # -> rational


,
( self number.abs ) <= rational and rational <= ( self + number.abs )
2.1.rationalize # -> (21/10)

.to_s # -> string


.
"+Infinity" "-Infinity".
2.1.to_s # -> "2.1"

6.3.2.
.*(number) # -> result .
./(number) # -> result .
.**(number) # -> result .
.+(number) # -> result .
.-(number) # -> result .

"NaN",

6.4. (Rational)

65

6.3.3.
.finite? # -> bool
.
2.1.finite? # -> true

.infinite? # -> -1, nil, 1


.
, , , nil.
2.1.infinite? # -> nil

.nan? # -> bool


Float::NAN.
2.1.nan? # -> false

6.3.4.
.hash # -> integer
.
2.1.hash # -> 569222191

6.4. (Rational)
- , (a/b), a , b - .
.
.
.Rational( nom, denom = 1 ) # -> rational [Kernel]
(nom/denom).
Rational 2, 3 # -> (2/3)
Rational "2/3" # -> (2/3)
Rational 8, 3 # -> (8/3)
Rational 2.1, 3 # -> (4728779608739021/6755399441055744)

6.4.1.
.to_r # -> rational
.inspect # -> string
.
Rational( 2, 3 ).inspect # -> "(2/3)"

6.5. (Complex)

66

.to_s # -> string


.
Rational( 2, 3 ).to_s # -> "2/3"

.to_f # -> float


.
Rational( 2, 3 ).to_f # -> 0.6666666666666666

.to_i # -> integer


.
Rational( 2, 3 ).to_i # -> 0

6.4.2.
.*(number) # -> result .
.**(number) # -> result .
.+(number) # -> result .
.-(number) # -> result .
./(number) # -> result
: quo
.

6.4.3.
.rationalize( number = Flt::EPSILON ) # -> rational
,
self number.abs <= rational && rational <= self + number.abs

6.5. (Complex)
- (a+b*i),
a b - , i - .
Numeric ( , , %, number.div, number.divmod,
number.remainder, number.step).

:
Complex::I - .

6.5. (Complex)

67

.Complex( real, imag = 0 ) # -> complex [Kernel]


.
Complex 2, 3 # -> (2+3i)
Complex "2/3" # -> ((2/3)+0i)
Complex 8, 3 # -> (8+3i)
Complex 2.1, 3 # -> (2.1+3i)
Complex ?i # -> (0+1i)

::polar( magnitude, angle = 0.0 ) # -> complex


.
Complex.polar 2, 3 # -> (-1.9799849932008908+0.2822400161197344i)

::rect( real, imag = nil ) # -> complex


: rectangular
.
Complex.rect 2, 3 # -> (2+3i)

6.5.1.
.inspect # -> string
.
Complex( 2, 3 ).inspect # -> "(2+3i)"

.to_s # -> string


.
Complex( 2, 3 ).to_s # -> "2+3i"

.to_f # -> float


, .
Complex( 2, 3 ).to_f # -> error!

.to_i # -> integer


, .
Complex( 2, 3 ).to_i # -> error!

.to_r # -> rational


, .
Complex( 2, 3 ).to_r # -> error!

6.5. (Complex)

68

.rationalize( number = Flt::EPSILON ) # -> rational


, . .
Complex(3).rationalize true # -> (3/1)

6.5.2.
.*(number) # -> result
.
Complex( 2, 3 ) * 2 # -> (4+6i)

./(number) # -> result


: quo
.
Complex( 2, 3 ) / 2 # -> ((1/1)+(3/2)*i)

.**(number) # -> result


.
Complex(2, 3)**2 # -> (-5+12i)

.+(number) # -> result


.
Complex( 2, 3 ) + 2 # -> (4+3i)

.-(number) # -> result


.
Complex( 2, 3 ) - 2 # -> (0+3i)

.- # -> result
.
-Complex( 2, 3 ) # -> (-2-3i)

6.5.3.
.abs2 # -> number
.
Complex( 2, 3 ).abs2 # # -> 13

.numerator # -> complex


.
Complex( 2, 3 ).numerator # -> (2+3i)

.denominator # -> complex


( ).
Complex( 2, 3 ).denominator # -> 1

6.6. Math

69

.fdiv(number) # -> complex


.
Complex( 2, 3 ).fdiv 2 # -> (1.0+1.5i)

.abs # -> number


: magnitude
.
Complex( 2, 3 ).abs # -> 3.605551275463989

.arg # -> float


: angle, phase
.
Complex( 2, 3 ).arg # -> 0.982793723247329

.real # -> number


.
Complex( 2, 3 ).real # -> 2

.imag # -> number


: imaginary
.
Complex( 2, 3 ).imag # -> 3

.rect # -> float


: rectangular
.
Complex( 2, 3 ).rect # -> [2, 3]

.conj # -> complex


: conjugate
.
Complex( 2, 3 ).conj # -> (2-3i)

6.6. Math
. ( Math),
( , Math).
, . .

6.6. Math

:
Math::PI - ();
Math::E - e.
.acos(number) # -> float .
.acosh(number) # -> float .
.asin(number) # -> float .
.asinh(number) # -> float .
.atan(number) # -> float .
.atan2( first_number, second_number ) # -> float .
.atanh(number) # -> float .
.cbrt(number) # -> float .
.cos(number) # -> float ( ).
.cosh(number) # -> float ( ).
.erf(number) # -> float .
.erfc(number) # -> float .
.exp(number) # -> float e .
.frexp(number) # -> array
[
float

float, integer],

* 2**integer == number.

.gamma(number) # -> float .


.hypot( first_number, second_number ) # -> float .
.ldexp( float, integer ) # -> float
float

* 2**integer.

.lgamma(number) # -> array



[ Math.log( Math.gamma(number).abs), Math.gamma(number) < 0 ? -1: 1 ].

70

6.6. Math

.log( number, base = Math::E ) # -> float


.log10(number) # -> float .
.log2(number) # -> float 2.
.sin(number) # -> float ( ).
.sinh(number) # -> float ( ).
.sqrt(number) # -> float .
.tan(number) # -> float ( ).
.tanh(number) # -> float ( ).

71

7.1. (String)
: Comparable
,
. , , .
::new( string = ) # -> string
.
String.new # -> ""

7.1.1.
::try_convert(object) # -> string
.to_str. , nil.
String.try_convert [1] # -> nil

.to_s # -> string


: to_str
.to_sym # -> sym
.
"abc".to_sym # -> :abc
"123a".to_sym # -> :"123a"

.to_i( numeral_system = 10 ) # -> integer


. , .
, 0.

7.1. (String)

73

"1".to_i # -> 1
"1a".to_i # -> 1
"1x".to_i # -> 1
"1.2".to_i # -> 1
"4/2".to_i # -> 4
"1 + 2".to_i # -> 1
"1

2".to_i # -> 1

"1e2".to_i # -> 1
"1_2".to_i # -> 12
"0b01 ax".to_i # -> 0
"0x01 ax".to_i # -> 0
"1+1i".to_i # -> 1

.to_r # -> rational


.
, .
, (0/1).
"1".to_r # -> 1/1
"1a".to_r # -> 1/1
"1x".to_r # -> 1/1
"1.2".to_r # -> 6/5
"4/2".to_r # -> 2/1
"1 + 2".to_r # -> 1/1
"1

2".to_r # -> 1/1

"1e2".to_r # -> 100/1


"1_2".to_r # -> 12/1
"0b01 ax".to_r # -> 0/1
"0x01 ax".to_r # -> 0/1
"1+1i".to_r # -> 1/1

.to_f # -> float


.
, .
, 0.0.

7.1. (String)

74

"1".to_f # -> 1.0


"1a".to_f # -> 1.0
"1x".to_f # -> 1.0
"1.2".to_f # -> 1.2
"4/2".to_f # -> 4.0
"1 + 2".to_f # -> 1.0
"1

2".to_f # -> 1.0

"1e2".to_f # -> 100.0


"1_2".to_f # -> 12.0
"0b01 ax".to_f # -> 0.0
"0x01 ax".to_f # -> 0.0
"1+1i".to_f # -> 1.0

.to_c # -> complex


.
, .
, (0+0i).
"1".to_c # -> 1+0i
"1a".to_c # -> 1+0i
"1x".to_c # -> 1+0i
"1.2".to_c # -> 1.2+0i
"4/2".to_c # -> 2/1+0i
"1 + 2".to_c # -> 1+0i
"1

2".to_c # -> 1+0i

"1e2".to_c # -> 100.0 + 0i


"1_2".to_c # -> 12+0i
"0b01 ax".to_c # -> 0+0i
"0x01 ax".to_c # -> 0+0i
"1+1i".to_c # -> 1+1i

.hex # -> integer


.
, . , 0.

7.1. (String)

75

"1".hex # -> 1
"1a".hex # -> 26
"1x".hex# -> 1
"1.2".hex # -> 1
"4/2".hex # -> 4
"1 + 2".hex # -> 1
"1

2".hex # -> 1

"1e2".hex # -> 482


"1_2".hex # -> 18
"0b01 ax".hex # -> 2817
"0x01 ax".hex # -> 1
"1+1i".hex # -> 1

.oct # -> integer


. , .
, 0.
"1".oct # -> 1
"1a".oct # -> 1
"1x".oct # -> 1
"1.2".oct # -> 1
"4/2".oct # -> 4
"1 + 2".oct # -> 1
"1

2".oct # -> 1

"1e2".oct # -> 1
"1_2".oct # -> 10
"0b01 ax".oct # -> 1
"0x01 ax".oct # -> 1
"1+1i".oct # -> 1

7.1.2.
, .
String [] []=, . .
, , -1.
string.[*object]
: slice(*object)
.[index] # -> string
. , nil.

7.1. (String)

76

"abc"[2] # -> "c"


"abc"[4] # -> nil

.[start, length] # -> string


.
,
;
, ("");
, nil;
, ("");
"abc"[ 2, 1 ] # -> "c"
"abc"[ 2, 2 ] # -> "c"
"abc"[ 2, 0 ] # -> ""
"abc"[ 2, -1 ] # -> nil
"abc"[ 3, 1 ] # -> ""

.[range] # -> string


.
,
;
, ,
("");
, nil.
"abc"[ 1..3 ] # -> "bc"
"abc"[ 1...3 ] # -> "bc"
"abc"[ 1...5 ] # -> "bc"
"abc"[ 1...0 ] # -> ""
"abc"[ 5...9 ] # -> nil

.[template] # -> string


, . , nil.
"abc"[ /[b-z]+/ ] # -> "bc"
"abc"[ /b-z+/ ] # -> nil

.[reg, group] # -> string


,
. , nil.
"abc"[ /(b)c/, 1 ] # -> "b"
"abc"[ /(b)c/, 3 ] # -> nil

7.1. (String)

77

string.[*object]=
, . .
.[index]=(string) # -> string
. .
"abc"[2] = "d" # -> "d"
"abc"[4] = "d"

# -> error!

.[start, length]=(string) # -> string


.
;
, ;
, ;
.
"abc"[ 4, 1 ] = "d" # -> error!
"abc"[ 3, 1 ] = "d" # -> "d"
string # -> "abdc"
"abc"[ 2, 1 ] = "d" # -> "d"
string # -> "abd"
"abc"[ 2, 2 ] = "d" # -> "d"
string # -> "abd"
"abc"[ 2, 0 ] = "d" # -> "d"
string # -> "abdc"
"abc"[ 2, -1 ] = "d" # -> error!

.[range]=(string) # -> string


.
,
;
, ,
, ;
.

7.1. (String)

78

"abc"[ 1...2 ] = "d" # -> "d"


string # -> "adc"
"abc"[1...5] = "d" # -> "d"
string # -> "ad"
"abc"[ 1...0 ] = "d" # -> "d"
string # -> "adbc"
"abc"[ 5...9 ] = "d" # -> error!

.[template]=(string) # -> string


, .
.
"abc"[ /[b-z]+/ ] = "d" # -> "d"
string # -> "ad"
"abc"[ /b-z+/ ] = "d" # -> error!

.[reg, group]=(string) # -> string


,
. .
"abc"[ /(b)c/, 1 ] = "d" # -> "d"
a # -> "adc"
"abc"[ /(b)c/, 3 ] = "d" # -> error!

.binslice(start, length = nil) # -> string


(range) # -> string

. .
.length # -> integer : size
.
"abc".length # -> 3

.bytesize # -> integer


, .
"abc".bytesize # -> 3

.getbyte(index) # -> integer


. ,
nil.
"abc".getbyte 0 # -> 97

7.1. (String)

79

.setbyte(index, byte) # -> integer


. .
"abc".setbyte 0, 120 # -> 120
string # -> "xbc"

7.1.3.
.%(object) # -> string .
.*(integer) # -> string .
.+(string) # -> text .
.(string) # -> text
: concat
.
.<=>(object) .
.=~(template) # -> integer
. , . , nil.
, object =~ string .

7.1.4.

.capitalize # -> string
,
- . ASCII .
"aBc".capitalize # -> "Abc"

.capitalize! # -> self


, .
.upcase # -> string
.
ASCII .
"aBc".upcase # -> "ABC"

7.1. (String)

80

.upcase! # -> self


, .
.downcase # -> string
.
ASCII .
"aBc".downcase # -> "abc"

.downcase! # -> self


, .
.swapcase # -> string
.
ASCII .
"aBc".swapcase # -> "AbC"

.swapcase! # -> self


, .

.clear # -> self
. .
"abc".clear # -> ""

.slice!(*object) # -> string


. , []=. .
"abc".slice! 2 # -> "c"
string # -> "ab"

.chomp( last = $/ ) # -> string


( - ). "abc".chomp ?c # -> "ab"
.chomp!( string = $/ ) # -> self
, .
, nil.
.chop # -> string
.
"abc".chop # -> "ab"

.chop! # -> self


, .
, nil.

7.1. (String)

81

.strip # -> string


(, , ) .
" abc ".strip # -> "abc"

.strip! # -> self


, .
, nil.
.lstrip # -> string
(, , ) .
" abc ".lstrip # -> "abc "

.lstrip! # -> self


, .
, nil.
.rstrip # -> string
(, , ) .
" abc ".rstrip # -> " abc"

.rstrip! # -> self


, .
, nil.

.insert(index, string) # -> self
.
"abc".insert 2, ?d # -> "abdc"
string # -> "abdc"

.prepend(string) # -> self


. .
"Ruby".prepend "Pure " # -> "Pure Ruby"

.center( length, string = ~ ) # -> text


( length). ,
, .
"abc".center 6, ?! # -> "!abc!!"

7.1. (String)

82

.ljust( length, string = ~ ) # -> text


( length). ,
, .
"abc".ljust 6, ?! # -> "abc!!!"

.rjust( length, string = ~ ) # -> text


( length). ,
, .
"abc".rjust 6, ?! # -> "!!!abc"


.dump # -> string
. . , ASCII .
"3\\n/2".dump # -> "\"3\\\\n/2\""
"3\\n/2".dump # -> "\"3\\\\n/2\\u{43b}\""

.inspect # -> string


. .
"3\verb!\n!/2".inspect # -> "\"3\\verb!\\n!/2\""
"3\verb!\n!/2".inspect # -> "\"3\\verb!\\n!/2\""

.next # -> string


: succ
. .
"xyz".next # -> "xza"

.next! # -> self


: succ!
, .
.reverse # -> string
.
"abc".reverse # -> "cba"

7.1. (String)

83

.reverse! # -> self


, .
.replace(string) # -> self
: initialize_copy
.
"abc".replace ?? # -> "?"

.unpack(string) # -> array


.
"\xFF\xFE\xFD".unpack "C*" # -> [ 255, 254, 253 ]

7.1.5.

.count(*template) # -> integer


.
^ () - ().
, .
"abc".count "a-z", "^c" # -> 2

.index( template, start = 0 ) # -> integer


, .
, nil.
"abbc".index /b/ # -> 1

.rindex( template, start = 0 ) # -> integer


,
(start).
, nil.
"abbc".rindex /b/ # -> 2

.match( template, start = 0 ) # -> match


( template, start = 0 ) { |match| } # -> object

. , nil.
.partition(template) # -> array
: ,
, .
,
, - ().
"abbc".partition /b/ # -> ["a", "b", "bc"]

7.1. (String)

84

.rpartition(template) # -> array


.
"abbc".rpartition /b/ # -> ["ab", "b", "c"]

.split( sep = $;, size = nil ) # -> array


( ). .
,
.
"a

c".split # -> [ "a", "b", "c" ]

"a

c".split // # -> [ "a", " ", " ", "b", " ", " ", "c" ]

"a

c".split //, 2 # -> [ "a", "

c" ]


.delete(*template) # -> string
. ^ () - ().
, .
"abc".delete "a-z", "^A-Z" # -> ""

.delete!(*template) # -> self


, .
, nil.
.squeeze(*template) # -> string
. ^ () - ().
, .
"aabbcc".squeeze "a-z", "^A-Z" # -> "abc"

.squeeze!(*template) # -> self


, .
, nil.

.gsub( template, replace ) # -> string
(template) { |match| } # -> string

. ,

85

7.1. (String)

, (
'\K <>' )

'\1'

"abcab".gsub /(a)b/, '\1' # -> "aca"


"abcab".gsub /(a)b/, 'ab' => ?y

# -> "ycy"

"abcab".gsub( /(a)b/ ) { |match| match.next } # -> "accac"

.gsub!( template, replace ) # -> self


(template) { |match| } # -> self

, .
, nil.
.sub( template, replace ) # -> string
(template) { |match| } # -> string

.
"abcab".sub /(a)b/, '\1'

# -> "acab"

"abcab".sub /(a)b/, 'ab' => ?y # -> "ycab"


"abcab".sub( /(a)b/ ) { |match| match.next } # -> "accab"

.sub!( template, replace ) # -> self


(template) { |match| } # -> self

, .
, nil.
.tr( template, replace ) # -> string
. ^ () - (),
-.
"abc".tr "^x-z", "X-Z" # -> "ZZZ"

.tr!( template, replace ) # -> self


, .
, nil.
.tr_s( template, replace ) # -> string
, .
"aabbcc".tr_s "^x-z", "X-Z" # -> "Z"

.tr_s!( template, replace ) # -> self


, .
, nil.

7.1. (String)

86

7.1.6.
.empty? # -> bool
("").
"abc".empty? # -> false

.ascii_only? # -> bool


ASCII .
"Helo".ascii_only? # -> false

.include?(template) # -> bool


.
"abc".include? "ab" # -> true

.end_with?(*template) # -> bool


. ,
.
"abc".end_with? "a", "c" # -> true

.start_with?(*template) # -> bool


. ,
.
"abc".start_with? "a", "c" # -> true

7.1.7.
.each_byte { |byte| } # -> self
: bytes
.
Ruby .bytes .
.each_char { |char| } # -> self : chars
.
Ruby .chars .
.each_line( sep = $/ ) { |line| } # -> self : lines
. (
- ).
Ruby .lines .
.each_codepoint { |point| } # -> self : codepoints
.
Ruby .codepoints .
.upto( last, ending = false ) { |string| } # -> self
self..last,
self...last ( true).

7.1. (String)

87

7.1.8.
.valid_encoding? # -> bool
.
.encoding # -> encoding
.
"".encoding # ->

#<Encoding:UTF-8>

.force_encoding(encoding) # -> self


.
.encode( encoding = Encoding.default_internal, options = {} ) # -> string
( encoding, result, options = {} ) # -> string

. .
.encode!( encoding = Encoding.default_internal, options = {} ) # -> self
( encoding, result, options = {} ) # -> self

, .
.b # -> copy_string [Ruby 2.0]
ASCII.

7.1.9.
.ord # -> integer
. .
"abc".ord # -> 97

.crypt(salt) # -> string


.
/[\w\d./]{2,2}/.
"abc".crypt "z1" # -> "z1Pgo5xjkEf8U"

.sum( salt = 16 ) # -> integer


. (

) % 2**salt - 1.

"abc".sum # -> 294

.hash # -> integer


.
"abc".hash # -> -913021130

.casecmp(object)
(<=>). .

7.2.

88

7.2.
7.2.1. Regexp

Regexp::IGNORECASE - ( i);
Regexp::EXTENDED -
( x);
Regexp::MULTILINE - ( m);
Regexp::FIXEDENCODING - .
::new( template, object = nil ) # -> regexp
: compile
. :
, ;
?n ?N, ASCII .
Regexp.new "abc", 2 # -> /abc/x

::union( *template array = nil ) # -> regexp


( ). /!?/.
Regexp.union [ ?0, ?1, ?2 ] # -> /0|1|2/


::try_convert(object) # -> regexp
.to_regexp.
, nil.
Regexp.try_convert "abc" # -> nil

.to_s # -> string


, .
/(a-z)/i.to_s # -> "(?i-mx:(a-z))"

.inspect # -> string


, .
/(a-z)/i.inspect # -> "/(a-z)/i"

.source # -> string


, c .
/(a-z)/i.source # -> "(a-z)"

7.2.

89

.===(string) # -> bool .


.=~(string) # -> integer .
.~(regexp) # -> integer
($_).

::last_match # -> match
(group) # -> string

. ,
nil.
.match( text, start = 0 ) # -> match
( text, start = 0 ) { |match| } # -> object

. , nil.

.encoding # -> encoding
.
/(a-z)/i.encoding # -> #<Encoding:US-ASCII>

.fixed_encoding? # -> bool


, ASCII.
/(a-z)/i.fixed_encoding? # -> false

.casefold? # -> bool


( i).
/(a-z)/i.casefold? # -> true

.named_captures # -> hash


, .
/(?<group>a-z)/i.named_captures # -> { "group" => [1] }

.names # -> array


.
/(?<group>a-z)/i.names # -> ["group"]

90

7.2.

.options # -> integer


.
/(a-z)/i.options # -> 1

.hash # -> integer


.
/(a-z)/i.hash # -> -145911848

::escape(text) # -> string


: quote
.
Regexp.new( Regexp.escape string ) =~

string # -> 0

Regexp.escape "'\*?{}.'" # -> "'\\*\\?\\{\\}\\.'"

7.2.2. MatchData
.

.to_s # -> string
.
.inspect # -> string
, .
.to_a # -> array
.

.[index] # -> string


(
- 0).
.[first, last] # -> array
, . ,
.
.[range] # -> array
, . ,
.

7.2.

91

.[name] # -> string


, .
.captures # -> array
, .
.offset(group) # -> array
,
.
.begin(group) # -> integer
, .
.end(group) # -> integer
, .
.pre_match # -> string
.
.post_match # -> string
.

.regexp # -> regexp


, .
.string # -> string
, .
.size # -> integer
: length
( ).
.names # -> array
, .
.hash # -> integer
.

7.3.

92

7.3.
7.3.1. (Encoding)
.
.
Encoding::UTF_8 # -> #<Encoding:UTF-8>


::default_external # -> encoding
, .
::default_external=(encoding) # -> encoding
, .
::default_internal # -> encoding
f, .
::default_internal=(encoding) # -> encoding
, . nil.
::locale_charmap # -> string
.
::list # -> array
.
::name_list # -> array
.
::aliases # -> hash
, .
::find(aliases) # -> encoding
, . (
nil).
:
external - ;
internal - ; locale - ; filesystem - .

7.3.

93

::compatible?( first_string, second_string ) # -> encoding


.
, , .
nil.
Encoding.compatible? "", "utf-8" # -> #<Encoding:UTF-8>

.inspect # -> string


.
Encoding::UTF_8.inspect # -> "#<Encoding:UTF-8>"

.name # -> string


: to_s
.
Encoding::UTF_8.name # -> "UTF-8"

.names # -> array


.
Encoding::UTF_8.names
# -> ["UTF-8", "CP65001", "locale", "external", "filesystem"]

.ascii_compatible? # -> bool


ASCII.
Encoding::UTF_8.ascii_compatible? # -> true

.dummy? # -> ruby


.
.
.
Encoding::UTF_8.dummy? # -> false

.replicate(name) # -> encoding


. .
Encoding::UTF_8.replicate "8" # -> #<Encoding:8>

7.3.2. (Encoding::Converter)

7.3.

94

:
::INVALID_MASK - ;
::INVALID_REPLACE - ;
::UNDEF_MASK - ;
::UNDEF_REPLACE - ;
::UNDEF_HEX_CHARREF -
&xHH;
::UNIVERSAL_NEWLINE_DECORATOR - CR (\r) CRLF (\r\n)
LF (\n);
::CRLF_NEWLINE_DECORATOR - LF (\n) CRLF (\r\n);
::CR_NEWLINE_DECORATOR - LF (\n) CR (\r);
::XML_TEXT_DECORATOR
::XML_ATTR_CONTENT_DECORATOR
::XML_ATTR_QUOTE_DECORATOR
::PARTIAL_INPUT - ;
::AFTER_OUTPUT - .
::new( source_enc, dest_enc, options = nil ) # -> converter
(conv_path) # -> converter

. . .
. .

::asciicompat_encoding(encoding) # -> encoding
, ASCII.
, nil.
Encoding::Converter.asciicompat_encoding "utf-8" # -> nil
Encoding::Converter.asciicompat_encoding "utf-16le"
# -> #<Encoding:UTF-8>

::search_convpath( source_enc, dest_enc, options = nil ) # -> array


.
Encoding::Converter.search_convpath "ISO-8859-1", "EUC-JP",
universal_newline: true
# -> [ [ #<Encoding:ISO-8859-1>, #<Encoding:UTF-8> ],
#

[ #<Encoding:UTF-8>, #<Encoding:EUC-JP> ],

"universal_newline" ]

7.3.

95

.inspect # -> string


.
Encoding::Converter.new( "ISO-8859-1", "EUC-JP" ).inspect
# -> "#<Encoding::Converter: ISO-8859-1 to EUC-JP>"

.convpath # -> array


.
Encoding::Converter.new( "ISO-8859-1", "EUC-JP" ).convpath
# -> [ [ #<Encoding:ISO-8859-1>, #<Encoding:UTF-8> ],
#

[ #<Encoding:UTF-8>, #<Encoding:EUC-JP> ] ]

.source_encoding # -> encoding


.
Encoding::Converter.new("ISO-8859-1",
"EUC-JP").source_encoding
# -> #<Encoding:ISO-8859-1>

.destination_encoding # -> encoding


.
Encoding::Converter.new("ISO-8859-1",
"EUC-JP").destination_encoding
# -> #<Encoding:EUC-JP>

.replacement # -> string


.
Encoding::Converter.new( "ISO-8859-1", "EUC-JP" ).replacement
# -> "?"

.replacement=(string) # -> string


,
.
.last_error # -> error
.

7.3.

96

.convert(text) # -> string


.
.
.primitive_convert( text, result, start = nil, bytesize = nil, options = nil )# > symbol

.
, ( ).

:
partial_input: true , ;
after_output: true , ,
.

( ):
(:invalid_byte_sequence);
.
, :partial_input (:incomplete_input);
(:undefined_conversion);
.
, :after_output (:after_output);
.
, bytesize nil (:destination_buffer_full);
.
, :partial_input (:source_buffer_empty);
(:finished).
.primitive_errinfo # -> array
:
[ symbol, source_enc, dest_enc, ivalid_byte, undef_char ],

symbol - .primitive_convert.
:invalid_byte_sequence,
:incomplete_input :undefined_conversion.
.putback # -> string
,
.primitive_convert.

7.3.

97

.insert_output(string) # -> nil


, .
, , .
.
.finish # -> string
.


: Enumerable

8.1. Array ( )
::new( size = 0, object = nil ) # -> array
(array) # -> array
(size) { |index| } # -> array

.
.
Array.new 3, ?R # -> ["R", "R", "R"]
Array.new [1, 2] # -> [1, 2]
Array.new(3) { |index| index**2 } # -> [0, 1, 4]

::[*object] # -> array


.
Array[1, 2, 3] # -> [1, 2, 3]

8.1.1.
.to_a # -> array
: to_ary
::try_convert(object) # -> array

object.to_ary. , nil.
Array.try_convert 1 # -> nil

.to_s # -> string


: inspect
.
[ 1, 2, 3 ].to_s # -> "[1, 2, 3]"

.join( sep = $, ) # -> string


(join - , .), ( nil).

8.1. Array ( )

99

[1, 2, 3].join # -> "123"


[
"#{msg}",
"Class: <#{e.class}>",
"Message: <#{e.message.inspect}>",
"---Backtrace---",
"#{MiniTest::filter_backtrace(e.backtrace).join("\n")}",
"---------------",
].join "\n"

.pack(format) # -> string


, apppack.
[-1, -2, -3].pack "C*" # -> "\xFF\xFE\xFD"

8.1.2.
[] []=. . , , -1.
- ,
.
array.[*object]
: slice(*object)
.[index] # -> object
: at
. , nil.
[1, 2, 3][2] # -> 3
[1, 2, 3][4] # -> nil

.[start, size] # -> array


.
,
;
,
([]);
, nil;
, .

8.1. Array ( )

100

[1, 2, 3][2, 1] # -> [3]


[1, 2, 3][2, 2] # -> [3]
[1, 2, 3][2, 0] # -> [ ]
[1, 2, 3][2, -1] # -> nil
[1, 2, 3][3, 1] # -> [ ]

.[range] # -> object


.
,
;
, ,
;
, nil.
[1, 2, 3][1...3] # -> [2, 3]
[1, 2, 3][1...5] # -> [2, 3]
[1, 2, 3][1...0] # -> [ ]
[1, 2, 3][5...9] # -> nil

array.[*object]=
. .
. nil.
.
.[index]=(object) # -> object
.
[1, 2, 3][2] = "d" # -> "d"
array # -> [1, 2, "d"]
[1, 2, 3][4] = "d"

# -> "d"

array # -> [1, 2, 3, "d"]

.[start, size]=(object) # -> object


.
, .
.

8.1. Array ( )

101

[1, 2, 3][4, 1] = "d" # -> "d"


array # -> [1, 2, 3, nil, "d"]
[1, 2, 3][3, 1] = "d" # -> "d"
array # -> [1, 2, 3, "d"]
[1, 2, 3][2, 1] = "d" # -> "d"
array # -> [1, 2, "d"]
[1, 2, 3][2, 2] = "d" # -> "d"
array # -> [1, 2, "d"]
[1, 2, 3][2, 0] = "d" # -> "d"
array # -> [1, 2, "d", 3]
[1, 2, 3][2, -1] = "d" # -> error!

.[range]=(object) # -> object


.
, , , .
[1, 2, 3][1...2] = "d" # -> "d"
array # ->[1, "d", 3]
[1, 2, 3][1...5] = "d"# -> "d"
array # -> [1, "d"]
[1, 2, 3][1...0] = "d"# -> "d"
array # -> [1, "d", 2, 3]
[1, 2, 3][5...9] = "d"# -> "d"
array # -> [1, 2, 3, nil, nil, "d"]

:
.fetch(index, object) # -> object2
(index) { |index| } # -> object

array[index]. .
[ 1, 2, 3 ].fetch 3, 4 # -> 4

.values_at(*object) # -> array


array[*object] .
[ 1, 2, 3 ].values_at 1, 1 # -> [ 2, 2 ]

8.1. Array ( )

102

.sample( size = nil ) # -> object


( size = nil, random: a_random ) # -> object [Ruby 2.0]

(
). nil . , .
[ 1, 2, 3 ].sample 4 # -> [ 2, 1, 3 ]

(Ruby 2.0).
.last(size = 1) # -> object
.
[ 1, 2, 3 ].last 2 # -> [ 2, 3 ]

.index(object) # -> integer


{ |object| } # -> integer

, .
[ 1, 2, 3 ].index { |elem| elem < 3 } # -> 0

.rindex(object) # -> integer


{ |object| } # -> integer

, .
[ 1, 2, 3 ].rindex { |elem| elem < 3 } # -> 1

8.1.3.
.*(integer) # -> array .
.*(sep) # -> string
.
[1, 2, 3] * ?? # -> "1?2?3"

.+(array) # -> new_array .


.-(array) # -> new_array .
.(object) # -> self . .
.&(array) # -> new_array .
.|(array) # -> array .

8.1. Array ( )

103

8.1.4.
.concat(array) # -> self
. .
[ "a", "b" ].concat [ "c", "d" ] # -> [ "a", "b", "c", "d" ]
a = [ 1, 2, 3 ]
a.concat [ 4, 5 ]
a # -> [ 1, 2, 3, 4, 5 ]


- , ,

. LIFO - ,
, .
Ruby .
.push(*object) # -> self
(
).
a = %w[ a b c ]
a.push 'd', 'e', 'f' # -> [ 'a', 'b', 'c', 'd', 'e', 'f' ]
[ 1, 2, 3 ].push(4).push(5) # -> [ 1, 2, 3, 4, 5 ]

.pop( size = 1 ) # -> object || array


(
). , nil.
a = %w[ a b c d ]
a.pop

# -> 'd'

a.pop 2 # -> [ 'b', 'c' ]


a

# -> ['a']

.unshift(*object) # -> self


(
).
a = %w[ b c d ]
a.unshift 'a'

# -> [ 'a', 'b', 'c', 'd' ]

a.unshift 1, 2 # -> [ 1, 2, 'a', 'b', 'c', 'd' ]

8.1. Array ( )

104

.shift( size = 1 ) # -> object || array


(
). , nil.
args = %w[ -m -q filename ]
args.shift

# -> '-m'

args

# -> [ '-q', 'filename' ]

args = %w[ -m -q filename ]


args.shift 2
args

# -> [ '-m', '-q' ]


# -> [ 'filename' ]


.clear # -> self
. .
[ 1, 2, 3 ].clear # -> [ ]

.compact # -> array


, nil.
[ 1, 2, 3 ].compact # -> [ 1, 2, 3 ]

.compact! # -> self


, .
.uniq # -> array
.
[ 1, 2, 3, 3, 2, 1 ].uniq # -> [ 1, 2, 3 ]

.uniq! # -> self


, .
, nil.
.slice!(*object) # -> delete
self[*object].
[1, 2, 3].slice! 1, 1 # -> [2]

.delete(object) # -> removed_object


(object) { }

,
( ). , nil, .

8.1. Array ( )

105

[ 1, 2, 3 ].delete(4) { "error!" } # -> "error!"


[ 1, 2, 3, 1 ].delete 1 # -> 1
array # -> [ 2, 3 ]
array = [ 2, 3, 4 ]
[ 1, 2, 3 ].each { |elem| array.delete elem } # -> [ 1, 2, 3 ]
array # -> [4]

.delete_at(index) # -> delete


( ). , nil.
[1, 2, 3].delete_at 1 # -> 2
array # -> [1, 3]

.delete_if { |object| } # -> self


: reject!
( ). ,
nil.
[1, 2, 3].delete_if { |elem| elem < 3 } # -> [3]

.select! { |object| } # -> self



( ). ,
nil. [1, 2, 3].select! { |elem| elem < 3 } # -> [1, 2]

.replace(array) # -> self
: initialize_copy
.
[1, 2, 3].replace [ ] # -> [ ]

.insert( *(index, *object) ) # -> self


array[integer]
.

= *object -

[ 1, 2, 3 ].insert 1, 2, 3 # -> [ 1, 2, 3, 2, 3 ]

.fill( object, start = 0, size = self.size ) # -> self


( start = 0, size = self.size ) { |index| } # -> self
( object, range ) # -> self
(range) { |index| } # -> self

( ).
, .
[1, 2, 3].fill 1 # -> [1, 1, 1]

8.1. Array ( )

106

.flatten( deep = nil ) # -> array


. .
[ [[1]], [[2]], [[3]] ].flatten # -> [1, 2, 3]

.flatten!(deep) # -> self

.
.rotate( step = 1 ) # -> array
.
[1, 2, 3].rotate

# -> [2, 3, 1]

[1, 2, 3].rotate -1

# -> [3, 1, 2]

.rotate!( step = 1 ) # -> self , .

8.1.5.
.reverse # -> array
.
[1, 2, 3].reverse # -> [3, 2, 1]

.reverse! # -> self


, .
.shuffle # -> array
(random: a_random) # -> array [Ruby 2.0]

. (Ruby 2.0).
[ 1, 2, 3 ].shuffle # -> [ 2, 3, 1 ]
[ 1, 2, 3 ].shuffle random: Random.new(1) # -> [ 1, 3, 2 ]

.shuffle! # -> self


(random: a_random) # -> self [Ruby 2.0]

, .
.sort! # -> self
{ |object, object2| } # -> self

8.1. Array ( )

107

( ). <=>,
.
.sort_by! { |object, object2| } # -> self
( ) .

8.1.6.
.each { |object| } # -> self .
.each_index { |index| } # -> self .
.collect! { |object| } # -> self
: map!
(
). .
[1, 2, 3].collect! { |elem| elem + 1 } # -> [2, 3, 4]
[1, 2, 3].collect! &:to_s # -> ["1", "2", "3"]

.combination(size) { |array| } # -> self


.
.
, [[]];
, , .
.repeated_combination(size) { |array| } # -> self
, .
.permutation( size = self.size ) { |array| } # -> self
, .
.repeated_permutation( size = self.size ) { |array| } # -> self
, .

8.1. Array ( )

108

8.1.7.
.assoc(key) # -> array
,
. , nil.
[ [:a, 1], [:b, 2], [:a, 3] ].assoc :a # -> [:a, 1]

.rassoc(object) # -> array


,
. , nil.
[ [:a, 1], [:b, 2], [:a, 3] ].rassoc :a # -> nil

.transpose # -> array



. , . , - .
[ [:a, 1], [:b, 1] ].transpose # -> [ [:a, :b], [1, 1] ]

8.1.8.
.product(*array) # -> array2
(*array) { |part| } # -> array3

self.size,
. .
.
, ;
,
.
[1, 2].product [3] # -> [ [1, 3], [2, 3] ]
[1, 2, 3].product # -> [ [1], [2], [3] ]
[1, 2, 3].product [ ] # -> [ ]

.bsearch { |x| } # -> elem [Ruby 2.0]


( , ). , O(log
n), n - . , .
, . ()
.

8.1. Array ( )

109


. i, :
false ,
i.
true ,
i.
i. , nil.
ary = [0, 4, 7, 10, 12]
ary.bsearch {|x| x >=

4 } # -> 4

ary.bsearch {|x| x >=

6 } # -> 7

ary.bsearch {|x| x >=

-1 } # -> 0

ary.bsearch {|x| x >= 100 } # -> nil

( )

F(x) = 0.
. i j (i <= j), :

0...i.
i...j.

j...size.

i...j. i == j, .. , ,
nil.
ary = [0, 4, 7, 10, 12]
# 4...8
ary.bsearch {|x| 1 - x / 4 } # -> 4 7
# 8...10
ary.bsearch {|x| 4 - x / 2 } # -> nil

.hash # -> integer


.
[1, 2, 3].hash # -> -831861323

110

8.2. Hash ( )

.empty? # -> bool


.
[1, 2, 3].empty? # -> false

.size # -> integer


: length
. , .
[ 1, 2, 3 ].size # -> 3

8.2. Hash ( )
::new( object = nil ) # -> hash
{ |hash, key| } # -> hash

.
::[ key, object ] # -> hash
[ *[key,object] ] # -> hash
[object] # -> hash

.
Hash[:Ruby, "languages", :Ivan, "man"]
# -> { Ruby: "languages", Ivan: "man" }
Hash[ [ [:Ruby, "languages"], [:Ivan, "man"] ] ]
# -> { Ruby: "languages", Ivan: "man" }
Hash[Ruby: "languages", Ivan: "man"]
# -> { Ruby: "languages", Ivan: "man" }

8.2.1.
.to_hash # -> hash
.to_h # -> self [Ruby 2.0]
, . , .
::try_convert(object) # -> hash
,
, nil.
Hash.try_convert[1] # -> nil

object.to_hash.

8.2. Hash ( )

111

.to_s # -> string


: inspect
. .
{ a: ?a, "b" => '\n' }.to_s # -> "{:a=>\"a\", \"b\"=>\"\\\\n\"}"

.to_a # -> array


[ *[key, object] ].
.
{ a: ?a, "b" => '\n' }.to_a # -> [ [:a, "a"], ["b", "\\n"] ]

8.2.2.
.[key] # -> object
. , .
{ a: ?a, "b" => 1 }[:a] # -> "a"

.values_at(*key) # -> array


.
{ a: ?a, "b" => 1 }.values_at :a, :b, ?b # ->

["a", nil, 1]

.select { |key, object| } # -> hash


, .
{ a: ?a, "b" => 1 }.select { |key| key == ?b } # -> { "b"=>1 }

.key(object) # -> key


.
, nil.
{ a: ?a, "b" => 1 }.key ?a # -> :a

.keys # -> array


.
{ a: ?a, "b" => 1 }.keys # -> [:a, "b"]

.values # -> array


.
{ a: ?a, "b" => 1 }.values # -> [ "a", 1 ]

.[key]=(object) # -> object


: store
.
{ a: ?a, "b" => 1 }[:a] = 2 # -> 2
hash # -> { :a => 2, "b" => 1 }

8.2. Hash ( )

112

.fetch( key, default = nil ) # -> object


(key) { |key| } # -> object

. ,
.
{ a: ?a, "b" => 1 }.fetch :b, ?a # -> "a"

8.2.3.

.merge(hash) # -> hash2
(hash) { |key, self_value, arg_value| } # -> hash2

. .
{ a: ?a, "b" => 1 }.merge( { "b" => ?b } ) # -> { a: "a", "b" => "b" }

.merge!(hash) # -> self


(hash) { |key, self_value, arg_value| } # -> self

: update
, .

.clear # -> self
( ).
{ a: ?a, "b" => 1 }.clear # -> { }

.shift # -> array


( ).
[key, value].
{ a: ?a, "b" => 1 }.shift # -> [ :a, "a" ]

.delete(key) # -> object


(key) { |key| } # -> object

( ). . ,
.
{ a: ?a, "b" => 1 }.delete :a # -> "a"
hash # -> { "b"=>1 }

8.2. Hash ( )

113

.delete_if { |key, value| } # -> self



( ).
{ a: ?a, "b" => 1 }.delete_if { |key| key == ?b } # -> { a: "a" }

.reject { |key, value| } # -> hash


, .
{ a: ?a, "b" => 1 }.reject { |key| key == ?b } # -> { a: "a" }

.reject! { |key, value| } # -> self || nil


, .
, nil.
{ a: ?a, "b" => 1 }.reject! { |key| key == ?c } # -> nil

.keep_if { |key, value| } # -> self


( ).
{ a: ?a, "b" => 1 }.keep_if { |key| key == ?b } # -> { "b"=>1 }

.select! { |key, value| } # -> self


, nil,
.
{ a: ?a, "b" => 1 }.select! { |key| key == ?b } # -> { "b"=>1 }

.replace(hash) # -> self


: initialize_copy
.
{ a: ?a, "b" => 1 }.replace( { } ) # -> { }

.invert # -> hash


.
{ a: ?a, "b" => 1 }.invert # -> { "a" => :a, 1 => "b" }

8.2.4.
.has_key?(key)
: include?, key?, member?
.
{ a: ?a, "b" => 1 }.has_key? :a # -> true

.has_value?(object)
: value?

8.2. Hash ( )

114

.
{ a: ?a, "b" => 1 }.has_value? :a # -> false

.compare_by_identity? # -> bool


-.
.empty? # -> bool
.
{ a: ?a, "b" => 1 }.empty? # -> false

8.2.5.
.each { |key, value| } # -> self
: each_pair
.
.each_key { |key| } # -> self .
.each_value { |value| } # -> self .

8.2.6.
.assoc(key) # -> array
,
. , nil. ==.
{ a: ?a, "b" => 1 }.assoc :a # -> [:a, "a"]

.rassoc(object) # -> array


, .
{ a: ?a, "b" => 1 }.rassoc ?a # -> [:a, "a"]

.flatten( deep = 0 ) # -> array


, . .
{ 1 => "one", 2 => [ [2], ["two"] ], 3 => "three" }.flatten 3
# -> [1, "one", 2, 2, "two", 3, "three"]

8.2.7.
.compare_by_identity # -> self
.

8.3. Range ()

115

{ a: ?a, "b" => 1 }.compare_by_identity


# -> { :a => "a", "b" => 1 }
hash[:a] # -> "a"
hash["b"] # -> nil
hash[:b] # -> nil
hash.key 1 # -> "b"

.size # -> integer


: length
.
{ a: ?a, "b" => 1 }.size # -> 2

.default # -> object .


.default_proc # -> proc
, ( nil).
.default=(object) # -> object
.
.default_proc=(proc) # -> proc
, .
nil (Ruby 2.0).
.hash # -> integer
.
{ a: ?a, "b" => 1 }.hash # -> -3034512

.rehash # -> hash .

8.3. Range ()
. .
::new( first, last, include_last = false ) # -> range
.
.
Range.new 1, 5, 0 # -> 1...5

116

8.3. Range ()

8.3.1.
.inspect # -> string
,
.

.inspect

(1..3).inspect # -> "1..3"

.to_s # -> string .


(1..3).to_s # -> "1..3"

8.3.2.
.begin # -> object
.
(1..3).begin # -> 1

.end # -> object


.
(1..3).end # -> 3

.last( size = nil ) # -> array


.
(1..3).last 2 # -> [ 2, 3 ]

8.3.3.
.===(object)
: cover?, member?, include?
. (1..3)

=== 2 # -> true

8.3.4.
.each { |object| } # -> self .succ.
.step( step = 1 ) { |object| } # -> self
, , .succ.

117

8.3. Range ()

8.3.5.
.exclude_end? # -> bool
.
(1..3).exclude_end? # -> false

.bsearch { |x| } # -> elem [Ruby 2.0]


( , ). , O(log
n), n - . ,
.
, .

. x, :
false x.
true , x.
x nil.
ary = [0, 4, 7, 10, 12]
(0...ary.size).bsearch { |i| ary[i] >= 4 } # -> 1
(0...ary.size).bsearch { |i| ary[i] >= 6 } # -> 2
(0...ary.size).bsearch { |i| ary[i] >= 8 } # -> 3
(0...ary.size).bsearch { |i| ary[i] >= 100 } # -> nil
(0.0...Float::INFINITY).bsearch { |x| Math.log(x) >= 0 } # -> 1.0

( )

F(x) = 0.
. x y (x <= y), :
x.
x...v.
y.

, , nil.

x...y.

8.4. Enumerator ()

118

ary = [0, 100, 100, 100, 200]


(0..4).bsearch { |i| 100 - ary[i] } # -> 1, 2 3
(0..4).bsearch { |i| 300 - ary[i] } # -> nil
(0..4).bsearch { |i|

50 - ary[i] } # -> nil

.hash # -> integer


. (1..3).hash

# -> -337569967

8.4. Enumerator ()
- , ,
.
.
, .
::new( object, method, *arg ) # -> enum
{ |enum| } # -> enum

.
.
enum << object ( yield).
.
Enumerator.new( [1, 2, ?R], :delete_at, 2 )
# -> #<Enumerator: [1, 2, "R"]:delete_at(2)>
Enumerator.new { |enum| enum << 3 }
# -> #<Enumerator: <Enumerator::Generator:0x87378e8>:each>

.enum_for( method = :each, *arg ) # -> enum


: to_enum
.
[1, 2, ?R].enum_for # -> #<Enumerator: [1, 2, "R"]:each>

Ruby ,
( ).

8.4. Enumerator ()

119

module Enumerable
# .
def repeat(n)
raise ArgumentError, "#{n} is negative!" if n < 0
if block_given?
each { |*val| n.times { yield *val } }
else
# __method__ == :repeat
enum_for( __method__, n ) { size * n if size }
end
end
end
enum = (1..14).repeat(3)
enum.first(4) # -> [1, 1, 1, 2]
enum.size # -> 42

8.4.1.
.inspect # -> string
.
Enumerate.new( [1, 2, ?R], :delete_at, 2 ).inspect
# -> "#<Enumerator: [1, 2, \"R\"]:delete_at(2)>"

8.4.2.
.next # -> object
. StopIteration.
.next_values # -> array
, .
yield
yield nil.
.peek # -> object
. StopIteration.
.peek_values # -> array
, .
yield
yield nil.
.rewind # -> enum
.

8.4. Enumerator ()

120

8.4.3.
.each( start = 0 ) { |object| } # -> self .
.with_index( start = 0 ) { |object, index| } # -> self
.
.with_object(object) { |object2, object| } # -> object
.

8.4.4.
.feed( object = nil ) # -> nil
.
, yield nil.
.size # -> integer [Ruby 2.0]
.
, nil.
(1..100).to_a.permutation(4).size # -> 94109400
loop.size # -> Float::INFINITY
(1..100).drop_while.size # -> nil

8.4.5. (Enumerator::Lazy)
( Enemerator).
Ruby ( )
.
, .
::new( enum, size = nil ) { | yielder, *values | } # -> a_lazy_enum
. , .

8.4. Enumerator ()

121

# .
module Enumerable
def filter_map(&block)
map(&block).compact
end
end
# .
class Enumerator::Lazy
def filter_map
Lazy.new(self) do | yielder, *values |
result = yield *values
yielder << result if result
end
end
end
(1..Float::INFINITY).lazy.filter_map{ |i| i*i if i.even? }.first(5)
# -> [ 4, 16, 36, 64, 100 ]

.lazy # -> a_lazy_enum


,
.
[1,2,3].lazy # -> #<Enumerator::Lazy: [1, 2, 3]>

.force # -> array


: to_a
.
.collect_concat { |object| } # -> a_lazy_enum
: flat_map
, .
[ 'foo', 'bar' ].lazy.flat_map { |i| i.each_char.lazy }.force
# -> [ 'f', 'o', 'o', 'b', 'a', 'r' ]

,
( .each .force) (
.to_ary).
[ {a:1}, {b:2} ].lazy.flat_map { |i| i }.force
#=> [ {a:1}, {b:2} ]

8.5. Enumerable

122

.enum_for( method = :each, *args ) # -> a_lazy_enum


( method = :each, *args ) { |*args| } # -> a_lazy_enum

: to_enum
Kernel.
, Enumerable ,
.
r = 1..Float::INFINITY
# .
r.repeat(2).first(5) # -> [ 1, 1, 2, 2, 3 ]
r.repeat(2).class # -> Enumerator
r.repeat(2).map{ |n| n ** 2 }.first(5) # -> !
# .
r.lazy.repeat(2).class # -> Enumerator::Lazy
r.lazy.repeat(2).map{ |n| n ** 2 }.first(5) # -> [ 1, 1, 4, 4, 9 ]

;
.
lines = File.foreach('a_very_large_file')
.lazy # .
.select { |line| line.length < 10 }
.map(&:chomp)
.each_slice(3)
.map { |lines| lines.join(';').downcase }
.take_while { |line| line.length > 20 }
#
# 20 .
lines.first(3)
lines.to_a # ...
lines.force #
lines.each { |elem| puts elem } # .

8.5. Enumerable
, .each.

<=>.

8.5. Enumerable

123


.to_a.

8.5.1.
.to_a # -> array
: entry
.

8.5.2.
.first( size = nil ) # -> object
. , .
[1, 2, 3].first 2 # -> [1, 2]

.take(size) # -> array


. , .
[1, 2, 3].take 2 # -> [1, 2]

.drop(size) # -> array


.
[1, 2, 3].drop 2 # -> [3]

8.5.3.
.sort # -> array
{ |first, second| } # -> array

<=>,
.
{ a: 1, b: 2, c: 3 }.sort # -> [ [:a, 1], [:b, 2], [:c, 3] ]

.sort_by { |first, second| } # -> array



.
{ a: 1, b: 2, c: 3 }.sort_by { |array| -array[1] }
# -> [ [:c, 3], [:b, 2], [:a, 1] ]

.group_by { |object| } # -> hash


.
[1, 2].group_by { |elem| elem > 4 } # -> { false => [1, 2] }

8.5. Enumerable

124

.zip(*object) # -> array


(*object) { |array| } # -> nil

.
.
, .
, nil.
{ a: 1, b: 2 }.zip [1, 2], [1]
# -> [ [ [:a, 1], 1, 1 ], [ [:b, 2], 2, nil ] ]

.chunk { |object| } # -> enum


(buffer) { |object, buffer| } # -> enum

.
.
:
nil :_ - ;
:_alone - .
.slice_before(object) # -> enum
{ |object| } # -> enum
(buffer

{ |object, buffer| } # -> enum

. ( ===), .
.
.

8.5.4.
.count( object = nil ) # -> integer
{ |object| } # -> integer

, , . .
[ 1, 2, 3 ].count { |elem| elem < 4 } # -> 3

.grep(object) # -> array


(object) { |object| } # -> array

,
( ===).

8.5. Enumerable

125

.
[ 1, 2, 3 ].grep(2) { |elem| elem > 4 } # -> [false]

.find_all { |object| } # -> array


: select

.
[1, 2, 3].find_all { |elem| elem > 4 } # -> [ ]

.reject { |object| } # -> array



.
[1, 2, 3].reject { |elem| elem > 4 } # -> [1, 2, 3]

.partition { |object| } # -> array


.
[1, 2, 3].partition { |elem| elem > 2 } # -> [ [3], [1, 2] ]

.detect( default = nil ) { |elem| } # -> object


: find

. , nil, .
[1, 2, 3].detect { |elem| elem > 4 } # -> nil

.find_index( object = nil ) # -> index


{ |object| } # -> index

, , .
, nil.
[1, 2, 3].find_index { |elem| elem > 4 } # -> nil

8.5.5.
<=>.
.min # -> object
.
[1, 2, 3].min # -> 1

.max # -> object


.
[1, 2, 3].max # -> 3

.minmax # -> array


.
[1, 2, 3].minmax # -> [1, 3]

8.5. Enumerable

126

.min_by { |object| } # -> object


.
[1, 2, 3].min_by { |elem| -elem } # -> 3

.max_by { |object| } # -> object


.
[1, 2, 3].max_by { |elem| -elem } # -> 1

.minmax_by { |object| } # -> array


.
[1, 2, 3].minmax_by { |elem| -elem } # -> [3, 1]

8.5.6.
.include?(object)
: member?
, ( ==).
[1, 2, 3].include? 4

# -> false

.all? { |object| }
.
.
[1, 2, 3].all? { |elem| elem < 4 } # -> true

.any? { |object| }

. .
[1, 2, 3].any? { |elem| elem < 4 } # -> true

.one? { |object| }
. .
[1, 2, 3].one? { |elem| elem < 4 } # -> false

.none? { |object| }
.
.
[1, 2, 3].none? { |elem| elem < 4 } # -> false

8.5.7.
.collect { |object| } # -> array
: map, collect_concat, flat_map
.

8.5. Enumerable

127

[1, 2, 3].collect { |elem| elem < 4 } # -> [true, true, true]


(1..3).collect(&:next) * ?| # -> "2|3|4"

.reverse_each( *arg ) { |object| } # -> self


.
.each_with_index { |object, index| } # -> self
.
.each_with_object(object) { |elem, object| } # -> object
.
.each_slice(size) { |array| } # -> nil
.
.each_cons(size) { |array| } # -> nil
.
,
.
.each_entry { |object| } # -> nil
. , yield
.each, .

8.5.8.
.drop_while { |object| } # -> array

. ,
.
. [1, 2, 3].drop_while { |elem| elem < 4 } # -> [ ]
.take_while { |object| } # -> array

. ,
.
.
[1, 2, 3].take_while { |elem| elem < 4 } # -> [1, 2, 3]

.cycle( step = nil ) { |object| } # -> nil


. . ,
.

8.5. Enumerable

128

8.5.9.
.lazy # -> a_lazy_enumerator [Ruby 2.0]
,
.
.inject(method) # -> object
(first, method) # -> object
(first = nil) { |buffer, first| } # -> buffer

: reduce
, . .

.
[1, 2, 3].inject( 100, :+ ) # -> 106

9.1.
- ,
.

Object, Class, Module.
Ruby . Class Module, Kernel.

9.1.1.

.

:
# -> expression;
# -> global-variable;
# -> local-variable;
# -> class-variable;
# -> instance-variable;
# -> constant;
true # -> true;
false # -> false;
nil # -> nil;
self # -> self;
yield # -> yield;
super # -> super;
# -> assignment;
# -> method.

defined?,

9.1.

130

9.1.2.
.class # -> class [Object]
.
1.class # -> Fixnum

.singleton_class # -> class [Object]


.
nil, true, false NilClass, TrueClass, FalseClass .
.
?1.singleton_class # -> #<Class:#<String:0x921114c>>

.nil? # -> [Object]


. nil true.
.===(object) # -> [Module]
.
Fixnum === 1 # -> true
Integer === 1 # -> true
Comparable === 1 # -> true

case, .
.is_a?(module) # -> [Object]
: kind_of?
.
1.is_a? Fixnum # -> true
1.is_a? Integer # -> true
1.is_a? Comparable # -> true

.instance_of?(module) # -> [Object]


.
1.instance_of? Fixnum # -> true
1.instance_of? Integer # -> false
1.instance_of? Comparable # -> false

9.1.

131

9.1.3.
.superclass # -> class [Class]
. BasicObject nil.
Fixnum.superclass # -> Integer

.name # -> string [Module]


. nil.
Fixnum.name # -> "Fixnum"

.to_s # -> string [Module]


( ). nil.
Fixnum.to_s # -> "Fixnum"

.ancestors # -> array [Module]


, .
Fixnum.ancestors
# -> [Fixnum, Integer, Numeric, Comparable, Object, Kernel, BasicObject]

.included_modules # -> array [Module]


.
Fixnum.included_modules # -> [ Comparable, Kernel ]

.include?(module) # -> [Module]


.
Fixnum.include? Comparable # -> true

.<=>(module) # -> -1. 0, 1 nil [Module]


.
-1 - ;
0 - ;
1 - ;
nil - .
.<(module) # -> [Module]
.
, nil.
Integer < Numeric # -> true
Numeric < Comparable # -> true
Integer < Comparable # -> true

.>(module) # -> [Module]


.
, nil.

9.1.

132

Integer > Numeric # -> false


Numeric > Comparable # -> false
Integer > Comparable # -> false

.<=(module) # -> [Module]


.
, nil.
Integer <= Integer # -> true
Numeric <= Comparable # -> true
Integer <= Comparable # -> true

.>=(module) # -> [Module]


.
, nil.
Integer >= Integer # -> true
Numeric => Comparable # -> false
Integer => Comparable # -> false

9.1.4.
.to_s # -> string [Object]
.
.inspect # -> string [Object]
. .
Ruby .to_s .
.object_id # -> integer [Object]
.
1.object_id # -> 3

.__id__ # -> integer [Object]


.
1.__id__ # -> 3

.constants( inherited = true ) # -> array [Module]


.
.

9.1.

133

.const_defined?( name, inherited = true ) # -> [Module]


.
.
Comparable.const_defined? :Fixnum # -> true

.const_get( name, inherited = true ) # -> object [Module]


. NameError.
.
Ruby .
const_get("Foo::Bar") # -> 'Foo Bar!'


.class_variables # -> array
.
.class_variable_defined?(name)
.
.class_variable_get(name) # -> object
. NameError.

.instance_variables # -> array
()
.
.instance_variable_defined?(name)
.
.instance_variable_get(name) # -> object
. NameError.

9.1.5.
.respond_to?( method, include_private = false ) # -> [Object]
.
.

9.1.

134

Ruby
. Ruby .
,
.respond_to_missing?.
.singleton_methods( inherited = true ) # -> array [Object]
.
.methods( inherited = false ) # -> array [Object]
.
.public_methods( inherited = true ) # -> array [Object]
.
.protected_methods( inherited = true ) # -> array [Object]
.
.private_methods( inherited = true ) # -> array [Object]
.
.instance_methods( inherited = false ) # -> array [Module]
.
.public_instance_methods( inherited = true ) # -> array [Module]
.
.protected_instance_methods( inherited = true) # -> array [Module]
.
.private_instance_methods( inherited = true ) # -> array [Module]
.
.method_defined?(name) # -> [Module]
.
Fixnum.method_defined? :next -> true

.public_method_defined?(name) # -> [Module]


.
Fixnum.public_method_defined? :next -> true

.protected_method_defined?(name) # -> [Module]


.
Fixnum.protected_method_defined? :next -> false

.private_method_defined?(name) # -> [Module]


.
Fixnum.private_method_defined? :next -> false

9.2.

135

.block_given? # -> bool [Kernel]


: iterator?
.

9.2.
- , , ,
.

9.2.1.
.binding # -> binding [PRIVATE: Kernel]
.
kernel.eval.
.eval( code, file = nil, line = nil ) # -> object [Binding]
, . .
.eval( code, binding = nil, file = nil, line = nil ) # -> object [PRIVATE: Kernel]
{ } # -> object

. .
.module_exec(*arg) { |*arg| } # -> self [Module]
: class_exec
.
.module_eval( code, file = nil, line = nil ) # -> self [Module]
{ } # -> self

: class_eval
.
.
.instance_exec(*arg) { |*arg| } # -> self [Object]
( self ).
.instance_eval( code, file = nil, line = nil ) # -> object [Object]
{ } # -> self

( self ).
.

9.2.

136

.tap { |object| } # -> object [Object]


,
.

9.2.2.
.send( name, *arg ) # -> [Object]
: __send__
.
.
.public_send( name, *arg ) # -> [Object]
. . ,
.

9.2.3.
- ,
.
, .
.method_missing(name, *arg)
.
.respond_to_missing?( name, include_private = nil )
object.respond_to? .
Ruby .
.const_missing(name)
.
.singleton_method_added(name)
.
.singleton_method_removed(name)
.
.singleton_method_undefined(name)
.
.method_added(name)
.

9.2.

137

.method_removed(name)
.
.method_undefined(name)
.
.inherited(class)
.
.append_features(module)
, . ,
, .
.prepend_features(module)
,
. , , , .
Ruby.
.extended(module)
.
.included(module)
.
.prepended(module)
.
Ruby.
module A
def self.prepended(mod)
puts "#{self} prepended to #{mod}"
end
end
module Enumerable
prepend A
end
# -> "A prepended to Enumerable"

9.2.

138

9.2.4.
.const_set( name, object ) # -> object [Module]
.
.remove_const(name) # -> object [PRIVATE: Module]
.
.
.class_variable_set( sym, obj ) # -> object [Module]
.
.remove_class_variable(name) # -> object [Module]
.
.instance_variable_set( name, object ) # -> object [Object]
.
.remove_instance_variable(name) # -> object [PRIVATE: Object]
.

9.2.5.
.define_singleton_method( name, block ) # -> block [Object]
.
.define_method(name) { } # -> proc [PRIVATE: Object]
(name, method) # -> new_method [Ruby 2.0]

.
, .
(
.instance_eval).
Ruby .

9.2.

139

class A
def fred; puts "In Fred"; end
def create_method(name, &block)
self.class.send(:define_method, name, &block)
end
define_method(:wilma) { puts "Charge it!" }
end
class B < A
define_method(:barney, instance_method(:fred))
end
a = B.new
a.barney # -> 'In Fred'
a.wilma # -> 'Charge it!'
a.create_method(:betty) { p self }
a.betty # -> '#<B:0x97dccfc>'

Ruby .
# 1.9.3
define_method(:hello) { "Hello World!" } # -> NoMethodError!
# 2.0.0
define_method(:hello) { "Hello World!" }
hello # -> "Hello World!"

.alias_method( new_name, old_name ) # -> self [PRIVATE: Module]


.
.remove_method(name) # -> self [PRIVATE: Module]
.
.
.undef_method(name) # -> self [PRIVATE: Module]
.

9.3.

140

9.3.
9.3.1.
-
.
:
Ruby , .
, , object.to_i, object.to_s, object.to_a, object.to_f, object.to_c,
object.to_r, object.to_h (ruby 2.0) ..
, , object.to_int, object.to_str, object.to_ary, object.to_sym,
object.to_regexp, object.to_proc, object.to_hash ..

Kernel. nil.
.Array(object) # -> array
1.

object.to_ary

2.

object.to_a

.Float(object) # -> float


1.

object.to_f

.Integer( object, numeral_system = 10 ) # -> integer


1.

object.to_int

2.

object.to_i

, ( 2 36). 0b (0B) 0x (0X).


.
.String(object) # -> string
1.

object.to_s

.Hash(object) # -> hash [Ruby 2.0]


1.

object.to_hash

141

9.3.

nil {}.
Hash([])

# -> {}

Hash(nil)

# -> {}

Hash(key: :value) # -> {:key => :value}


Hash( [1, 2, 3] ) # -> TypeError!

.format( format, *object ) # -> string


: sprintf
format

% [*object].

9.3.2.

.==(object) # -> [Object]
: ===
.
1 == 1.0 -> true

.eql?(object) # -> [Object]


.
1.eql? 1.0 -> false

.equal?(object) # -> [Object]


.
1.equal? 1.0 -> false
"1".equal? "1" -> false
1.equal? 1 -> true
:a.equal? :a -> true

Comparable
(<, <=, >, >=, ==), .<=>.
.between?( first, last )
.

9.3.3.

,
.
.
, .

9.3.

142

a = { t1: 'sa ma ra', t2: 'john' }


b = a.clone
b[:t2] = 'jack'
b[:t1].sub!('ma', 'ha')
a[:t1] == 'sa ha ra' # -> true

.clone # -> object [Object]


, .
.dup # -> object [Object]
, .
.initialize_clone(object) # -> object
,
( ). .
Ruby .
.initialize_dup(object) # -> object
, ( ). .
Ruby .
.initialize_copy(object) # -> object
( ).
.

9.3.

143

class Object
def clone
clone = self.class.allocate
clone.copy_instance_variables(self)
clone.copy_singleton_class(self)
clone.initialize_clone(self)
clone.freeze if frozen?
clone
end
def dup
dup = self.class.allocate
dup.copy_instance_variables(self)
dup.initialize_dup(self)
dup
end
def initialize_clone(other)
initialize_copy(other)
end
def initialize_dup(other)
initialize_copy(other)
end
def initialize_copy(other)
# ...
end
end

(Marshal)
,
(
).

:
Marshal::MAJOR_VERSION - ;
Marshal::MINOR_VERSION - .

9.3.

144

::dup( object, io = nil, deep = -1 ) # -> string


.
( ).
, .
:
;
, (, , .);
MatchData, Data, Method, UnboundMethod, Proc, Thread,
ThreadGroup, Continuation;
, .
Marshal.dump ?$ # -> "\x04\bI\"\x06$\x06:\x06ET"

::load(marshal_data) # -> object


(marshal_data) { |result| } # -> object

: restore
.
Marshal.load Marshal.dump(?$) # -> "$"

10

- ,
. ( ), .

10.1. (Proc)
(. closure) - ,
,
( ).
,
.
.
, .
.
.
self , .
class FirstKlass
def self.first; 1; end
def first; 2; end
@@first = proc { first }
def klass; @@first.call; end
def instance; instance_exec &@@first; end
end
FirstKlass.new.klass # -> 1
FirstKlass.new.instance # -> 2

( , ) - (
).

10.1. (Proc)

146

10.1.1.
return , . ,
LocalJumpError.
.
::new { |*params| } # -> proc
.
def proc_from
Proc.new
end
proc = proc_from { "hello" }
proc.call # -> "hello"

.proc { |*params| } # -> proc [PRIVATE: Kernel]


Kernel.
def foo
f = Proc.new { return "return from foo from inside proc" }
f.call # f foo
# foo f
return "return from foo"
end
puts foo # "return from foo from inside proc"

10.1.2. -
return - .
- .
.
. .
->(*params) { } # -> lambda

.lambda { |*params| } # -> lambda


.
def bar
f = lambda { return "return from lambda" }
f.call # f bar
return "return from bar"
end
puts bar # "return from bar"

10.1. (Proc)

147

10.1.3.

.to_proc # -> self
.to_s # -> string
.
Proc.new { }.to_s # -> "#<Proc:0x8850f18@(irb):31>"

.==(proc)
: eql?
. ,
.
proc {} == proc {} # -> true

Ruby . , .
proc {} == proc {} # -> false

.===(arg) # -> object


.
proc { |a| a } === 1 # -> 1


.call(*arg) # -> object
: yield, .(*arg), [*arg]
.
-> x {x**2}.(5) # -> 25

.curry( count = nil )*arg # -> proc


. ,
. .
( nil).

10.1. (Proc)

148

b = proc { | x, y, z | x + y + z }
b.curry[1][2][3] # -> 6
b.curry[1, 2][3, 4] # -> 6
b.curry[1][2][3][4][5] # -> 0
b.curry(5) [ 1, 2 ][ 3, 4][5] # -> 6
b.curry(1) [1] # -> type_error!
b = lambda { | x, y, z | x + y + z }
b.curry[1][2][3] # -> 6
b.curry[1, 2][3, 4] # -> argument_error!
b.curry(5) # -> argument_error!
b.curry(1) # -> argument_error!

.arity # -> integer


. . ~
.
proc {}.arity # -> 0
proc { || }.arity # -> 0
proc { |a| }.arity # -> 1
proc { |a, b| }.arity # -> 2
proc { |a, b, c| }.arity # -> 3
proc { |*a| }.arity # -> -1
proc { |a, *b| }.arity # -> -2
proc { | a, *b, c | }.arity # -> -3

.parameters # -> array


.
proc = lambda { | x, y = 42, *other | }
proc.parameters
# -> [ [:req, :x],

[:opt, :y], [:rest, :other] ]

.binding # -> binding


.
.lambda? # -> bool
-.
proc {}.lambda? # -> false

149

10.2.

.source_location # -> array



, Ruby, nil.

[filename, line].

proc {}.source_location # -> ["(irb)", 19]

.hash # -> integer


.
proc {}.hash # -> -259341767

- .
closure = proc { counter = 0; proc {counter += 1} }.call
closure.call # -> 1
closure.call # -> 2
closure.call # -> 3

10.2.

Method UnboundMethod.

10.2.1. Method
,
.
.method(name) # -> method
. .
12.method(?+) # -> #<Method: Fixnum#+>

.public_method(name) # -> method


.
12.public_method(?+) # -> #<Method: Fixnum#+>

.==(method)
: eql?
. , .
12.method(?+) == 13.method(?+) # -> false

150

10.2.


.to_proc # -> lambda
- .
12.method(?+).to_proc # -> #<Proc:0x88cdd60 (lambda)>

.to_s # -> string


.
12.method(?+).to_s # -> "#<Method: Fixnum#+>"

.unbind # -> umethod


,
.
12.method(?+).unbind -> #<UnboundMethod: Fixnum#+>


.call(*arg) # -> object
.
12.method(?+).call 3 # -> 15

.arity # -> integer


. . ~ . ,
Ruby -1.
12.method(?+).arity # -> 1

.name # -> symbol


.
12.method(?+).name # -> :+

.owner # -> module


, .
12.method(?+).owner # -> Fixnum

.parameters # -> array


.
12.method(?+).parameters # -> [ [:req] ]

.receiver # -> object


, . 12.method(?+).receiver

# -> 12

151

10.2.

.source_location # -> array


[filename,
, Ruby, nil.

line].

12.method(?+).source_location # -> nil

.hash # -> integer


.
12.method(?+).hash # -> -347045594

10.2.2. UnboundMethod
.
.instance_method(name) # -> umethod [Module]
.
.
Math.instance_method :sqrt # -> #<UnboundMethod: Math#sqrt>

.public_instance_method(name) # -> umethod [Module]


.
Math.public_instance_method :sqrt # -> error

.==(umethod)
: eql?
. ,
.
Math.instance_method(:sin) == Math.instance_method(:sin) # -> true


.to_s # -> string : inspect
.
Math.instance_method(:sqrt).to_s # -> "#<UnboundMethod: Math#sqrt>"

.bind(object) # -> method


, . , .
12.method(?+).unbind.bind 1 # -> #<Method: Fixnum#+>
12.method(?+).unbind.bind 1.0 # -> error!

152

10.3. (Fiber)

.arity # -> integer


. . ~ . ,
Ruby -1.
Math.instance_method(:sqrt).arity # -> 1

.name # -> symbol


.
Math.instance_method(:sqrt).name # -> :sqrt

.owner # -> module


, .
Math.instance_method(:sqrt).owner # -> Math

.parameters # -> array


.
Math.instance_method(:sqrt).parameters # -> [ [:req] ]

.source_location # -> array


[filename,
, Ruby, nil.

line].

Math.instance_method(:sqrt).source_location # -> nil

.hash # -> integer


.
Math.instance_method(:sqrt).hash # -> 563385534

10.3. (Fiber)
- ,
.
,
.

( ). green thread.

, .
,
. /,
.
.

10.3. (Fiber)

153

::yield .resume.
::new { |*params| } # -> fiber
. .
::yield(*temp_result) # -> object
. .resume.
, .resume .
.resume(*args) # -> temp_result
.
,
.
::yield .
, FiberError.

11

(Random)
Ruby
, 1997 . (2 ** 19937 - 1),
623 , ( 2-3 ,
). , , , , .
::new( seed = Random.new_seed ) # -> random
. , , . .
Random.new # -> #<Random:0xa0a1fa4>

::rand( number = 0 ) # -> random_number


.
number.to_i.abs:
nil,
0.0...1.0.

0...number.to_i.abs.
Random.rand # -> 0.8736231696463861

.rand( number = 0 ) # -> random_number [PRIVATE: Kernel]


Kernel.
::new_seed # -> integer
.
Random.new_seed # -> 69960780063826734370396971659065074316

::srand( number = 0 ) # -> number


. ,
, .
. .
.srand( number = 0 ) # -> number [PRIVATE: Kernel]
Kernel.

11.1.

155

11.1.
.bytes(bytesize) # -> string
.
Random.new.bytes 2 -> "\xA1W"

.rand( object = nil ) # -> number


, 0...object;
;
, 0.0...object;
, .
- () + ();
.
.seed # -> integer
.
Random.new.seed # -> 173038287409845379387953855893202182131

12


12.1. (Time)
: Comparable
Time - , . , 01.01.1970 00:00 UTC. GMT ( ) UTC ( )
.
,
UTC.

:
year - ;
month - : 1 12, ,
();
day - : 1 31;
wday - : 0 6, ;
yday - : 1 366;
isdst - : ;
zone - : ;
hour - : 0 23;
min - : 0 59;
sec - : 0 60;
usec - : 0 999.

12.1.1.
::new # -> time
(year, month = 1, day = 1, hour = 0, min = 0, sec = 0, usec = 0, zone)
# -> time

.
. UTC +00:00 .
.
Time.new 1990, 3, 31, nil, nil, nil, "+04:00"
# -> 1990-03-31 00:00:00 +0400

12.1. (Time)

157

::now # -> time


.
Time.now -> 2011-09-17 10:36:26 +0400

::at(time) # -> time


( sec, usec = nil ) # -> time

. ,
UTC.
.
Time.at 1 -> 1970-01-01 03:00:01 +0300

::utc( year, month = 1, day = 1, hour = 0, min = 0, sec = 0, usec = 0)


( sec, min, hour, day, month, year, wday, yday, isdst ) # -> time

: gm
.
Time.utc 1990, 3, 31 -> 1990-03-31 00:00:00 UTC

::local( year, month = 1, day = 1, hour = 0, min = 0, sec = 0, usec = 0, zone )


(sec, min, hour, day, month, year, wday, yday, isdst, zone) # -> time

: time
, .
Time.local 1990, 3, 31 -> 1990-03-31 00:00:00 +0400

12.1.2.
.to_s # -> string
: inspect
.
Time.local( 1990, 3, 31 ).to_s -> "1990-03-31 00:00:00 +0400"

.to_a # -> array


:
[ self.sec, self.min, self.hour,
self.day, self.month, self.year,
self.wday, self.yday,
self.isdst, self.zone ]
Time.local( 1990, 3, 31 ).to_a
# -> [ 0, 0, 0, 31, 3, 1990, 6, 90, true, "MSD" ]

.to_i # -> integer


: tv_sec
1970-01-01 00:00:00 UTC.
Time.local( 1990, 3, 31 ).to_i # -> 638827200

12.1. (Time)

158

.to_r # -> rational


1970-01-01 00:00:00 UTC .
Time.local( 1990, 3, 31 ).to_r # -> (638827200/1)

.to_f # -> float


1970-01-01 00:00:00 UTC .
Time.local( 1990, 3, 31 ).to_f # -> 638827200.0

12.1.3.
.+(number) # -> time
.
Time.local( 1990, 3, 31 ) + 3600 # -> 1990-03-31 01:00:00 +0400

.-(time) # -> float


.
Time.local( 1990, 3, 31 ) - Time.new( 1990, 3, 31 ) -> 0.0

.-(number) # -> time


.
Time.local( 1990, 3, 31 ) - 3600 -> 1990-03-30 23:00:00 +0400

.<=>(time)
.
Time.local( 1990, 3, 31 ) <=> Time.new( 1990, 3, 31 ) -> 0

12.1.4.
.strftime(format) # -> string

.

12.1.5.
.getutc # -> time
: getgm
UTC ( ).
Time.local( 1990, 3, 31 ).getutc # -> 1990-03-30 20:00:00 UTC

.utc # -> self


: gmtime
, .

12.1. (Time)

159

.getlocal( zone = nil ) # -> time


. ( ).
Time.local(1990, 3, 31).getutc.getlocal # -> 1990-03-31 00:00:00 +0400

.localtime( zone = nil ) # -> self


, .

12.1.6.
.asctime # -> string
: ctime
.
Time.local( 1990, 3, 31 ).asctime # -> "Sat Mar 31 00:00:00 1990"

.utc_offset # -> integer


: gmt_offset, gmtoff
UTC .
Time.local( 1990, 3, 31 ).utc_offset # -> 14400

.zone # -> string


.
verb!Time.local( 1990, 3, 31 ).zone # -> "MSD"

.year # -> integer


.
Time.local( 1990, 3, 31 ).year # -> 1990

.month # -> integer


: mon
.
verb!Time.local( 1990, 3, 31 ).month # -> 3

.yday # -> integer


1 366.
Time.local( 1990, 3, 31 ).yday # -> 90

.day # -> integer


: mday
.
Time.local( 1990, 3, 31 ).day # -> 31

.wday # -> integer


( 0 6, ).
Time.local( 1990, 3, 31 ).wday # -> 6

12.1. (Time)

.hour # -> integer


( 0 23).
Time.local( 1990, 3, 31 ).hour # -> 0

.min # -> integer


( 0 59).
Time.local( 1990, 3, 31 ).min # -> 0

.sec # -> integer


( 0 60).
Time.local( 1990, 3, 31 ).sec # -> 0

.subsec # -> integer


.
Time.local( 1990, 3, 31 ).subsec # -> 0

.usec # -> integer


: tv_usec
.
Time.local( 1990, 3, 31 ).usec # -> 0

.nsec # -> integer


: tv_nsec
.
Time.local( 1990, 3, 31 ).nsec # -> 0

12.1.7.
.monday? # -> bool
.
Time.local( 1990, 3, 31 ).monday? # -> false

.tuesday? # -> bool


.
Time.local( 1990, 3, 31 ).tuesday? # -> false

.wednesday? # -> bool


.
Time.local( 1990, 3, 31 ).wednesday? # -> false

.thursday? # -> bool


.
Time.local( 1990, 3, 31 ).saturday? # -> false

.friday? # -> bool


.
Time.local( 1990, 3, 31 ).friday? # -> false

160

12.1. (Time)

161

.saturday? # -> bool


.
Time.local( 1990, 3, 31 ).saturday? # -> true

.sunday? # -> bool


.
Time.local( 1990, 3, 31 ).saturday? # -> false

.utc? # -> bool


: gmt?
UTC.
Time.local( 1990, 3, 31 ).utc? # -> false

.dst? # -> bool


: isdst
.
Time.local( 1990, 3, 31 ).dst? # -> true

12.1.8.
.hash # -> integer
.
Time.local( 1990, 3, 31 ).hash # -> -494674000

.round( precise = 0 ) # -> time


. .
Time.local( 1990, 3, 31 ).round 2 # -> 1990-03-31 00:00:00 +0400

13


13.1.
TrueClass, FalseClass NilClass -
true, false nil . TRUE, FALSE, NIL,
( ?).
NilClass
nil & obj -> false
nil ~ bool -> bool
nil | bool -> bool
nil.to_s ->

FalseClass
false & obj -> false
false ~ bool -> bool
false | bool -> bool
false.to_s -> false

TrueClass
true & bool -> bool
true ~ bool -> !bool
true | object -> true
true.to_s -> true

nil.nil? # -> true


nil.inspect # -> "nil"
nil.rationalize # -> (0/1)
nil.to_r # -> (0/1)
nil.to_a # -> []
nil.to_c # -> (0+0i)
nil.to_f # -> 0.0
nil.to_i # -> 0
nil.to_h # -> {} [Ruby 2.0]

13.2. Symbol
: Comparable
.
::all_symbols # -> array .

13.2.1.
.to_sym # -> symbol : intern
.to_s # -> string
: id2name
.
:Ruby.to_s # -> "Ruby"

13.2. Symbol

163

.inspect # -> string


.
:Ruby.inspect # -> ":Ruby"

.to_proc # -> proc


, ,
.
1.next # -> 2
:next.to_proc.call(1) # -> 2

13.2.2.
symbol <=> object # -> symbol.to_s <=> object
symbol =~ object # -> symbol.to_s =~ object
symbol[*object] # -> symbol.to_s[*object]
symbol.slice(*object) # -> symbol.to_s.slice(*object)

13.2.3.
.capitalize # -> symbol : self.to_s.capitalize.to_sym.
.swapcase # -> symbol : self.to_s.swapcase.to_sym.
.upcase # -> symbol : self.to_s.upcase.to_sym.
.downcase # -> symbol : self.to_s.downcase.to_sym.

13.2.4.
.encoding # -> encoding
.
:Ruby.encoding # -> #<Encoding:US-ASCII>

.empty? # -> bool : self.to_s.empty?.


.length # -> integer
: size
: self.to_s.length self.to_s.size.
.casecmp(object)

: self.to_s.casecmp(object).

.next # -> symbol


: succ
: self.to_s.next.to_sym self.to_s.succ.to_sym

13.3.

164

13.3.
: Enumerable
- , .
.
Struct.
::new( name = nil, *attribute ) # -> class
Struct
( nil). ,
. ,
.
,
.
Struct.new "K", : # -> Struct::K
# . :)
Struct::K.new [1, 2, 3]
# ->

#<struct Struct::K =[1, 2, 3]>

13.3.1.
.to_s # -> string
: inspect
.
Struct::K.new( [1, 2, 3] ).to_s
# -> "#<struct Struct::K =[1, 2, 3]>"

.to_a # -> array


: values
.
Struct::K.new( [1, 2, 3] ).to_a # -> [ [1, 2, 3] ]

.to_h # -> hash [Ruby 2.0]


.
Customer = Struct.new :name, :address, :zip
joe = Customer.new "Joe Smith", "123 Maple, Anytown NC", 12345
joe.to_h[:address] # -> "123 Maple, Anytown NC"

13.3.

165

13.3.2.
. [] []=. .
0 ,
. (, -1).
.
.[attr] # -> object
.
Struct::K.new( [1, 2, 3] )[""] # -> [1, 2, 3]
Struct::K.new( [1, 2, 3] )[0] # -> [1, 2, 3]
Struct::K.new( [1, 2, 3] )[-1] # -> [1, 2, 3]

.[attr]=(object) # -> object


.
Struct::K.new( [1, 2, 3] )[""] = :array # -> :array
Struct::K.new( [1, 2, 3] )[0] = :array # -> :array
Struct::K.new( [1, 2, 3] )[-1] = :array # -> :array

.values_at(*integer) # -> array


. .
Struct::K.new( [1, 2, 3] ).values_at 0, -1
# -> [ [1, 2, 3], [1, 2, 3] ]

13.3.3.
.each { |object| } # -> self
.
.each_pair { | name, object | } # -> self
.

13.3.4.
.hash # -> integer
.
Struct::K.new( [1, 2, 3] ).hash # -> -764829164

.size # -> integer


: length

13.3.

.
Struct::K.new( [1, 2, 3] ).size # -> 1

.members # -> array


.
Struct::K.new( [1, 2, 3] ).members # -> [:]

166

III

14


14.1.
. :
ruby [keys] [path] [args]

keys - ,
;
path - . .
, , ,
( ).
args - ,
ARGV.
, ( ), (shebang)
:
#!/usr/bin/env ruby [keys] [args]


.
.
- , . Linux env.

14.2.
- .
: ,
.
BEGIN END - ,
.
.

14.3.

169

BEGIN - .
, ;
END - .
, . File, DATA;
__END__ - END;
at_exit - END.

14.3.
Kernel ( ,
).
.sleep( sec = nil ) # -> sec
( ). .
.exit( state = true )
SystemExit.
.exit!( state = false )
.
.abort( mesage = nil )
. .
exit false.

14.4.
Ruby ,
. Kernel.
.(code) # -> string
.
ruby --help

%x (%x[ruby --help]).
.exec( env, command, options )
. .

14.4.

170

Ruby
.

:
env (hash): .
name: ;
name: nil, .
command: .
string - : Unix "/bin/sh", Windows - ENV["RUBYSHELL"] ENV["COMSPEC"];
string, *arg - ;
[ string, first_arg ], *arg - , .
option (hash): .
unsetenv_others: true, , ;
pgroup: :
true ;
integer ;
nil .
chdir: ;
umask: .

.syscall( number, *args )



( Unix
syscall.h).
( ) ,
, .

SystemCallEror.
NotImplementedError.
.

15


15.1. IO ()
: Enumerable File::Constants
- ,
. () , -
() .

( , , ), .
/:
: . .
.
: . , .
(polling) .
.
: .
.
: (
).

15.1.1.
.

, .
, , IO.
::new( file, mode, options = nil ) # -> io
: for_fd

15.1. IO ()

172

, .
, .
::open( file, mode, options = nil ) # -> io
( file, mode, options = nil ) { |io| } # -> object

,
( ).
::sysopen( path, mode = nil, *perm ) # -> integer
.
.
::copy_stream( old_io, new_io, start = nil, syze = nil ) # -> integer
. . . ,
.

.reopen(io) # -> self
( path, mode ) # -> self

.
.binmode # -> self
.
.autoclose=(bool) # -> bool
.
.close_on_exec=(bool) # -> nil
.
Ruby
. .spawn.
.advise( symbol, start = 0, size = 0 ) # -> nil
.
, .
:normal - ( );
:sequintial - ; :random -
;
:willneed - ;
:dontneed - ;
:noreuse - .

15.1. IO ()

173

.fcntl( integer, object ) # -> integer2


. fcntl(2).
.ioctl( integer, object ) # -> integer2
. ioctl(2).

.
.close # -> nil
.
.close_read # -> nil
. ( ) .
.close_write # -> nil
.
( ) .

.external_encoding # -> encoding


. ,
, nil.
.internal_encoding # -> encoding
nil.
.set_encoding( *encoding, options = nil ) # -> io
. .

.autoclose? # -> bool


.
.binmode? # -> bool
.
.eof? # -> bool
: eof

15.1. IO ()

174

( ).
,
.
.tty? # -> bool
: isatty
. , , , .
,
.
.closed? # -> bool
.
.close_on_exec? # -> bool
.
f = open '/dev/null'
f.close_on_exec?

# -> false

f.close_on_exec = true
f.close_on_exec?

# -> true

f.close_on_exec = false
f.close_on_exec?

# -> false

.stat # -> a_file_stat


.

15.1.2.
::try_convert(object) # -> io

.to_io. , nil.
.to_i # -> integer
: fileno
.
.to_io # -> io

15.1. IO ()

175

15.1.3.
.
.

:
encoding: . ;
mode: . r ;
open_args: , .

::read( path, start = nil, bytesize = nil, options = nil ) # -> string
( ). .
, .
::binread( path, start = nil, size = nil ) # -> string
rb:ASCII.
.read( bytesize = nil, buffer = nil ) # -> buffer
( ).
, .
.
, ;
, nil
( ).
.
.sysread( bytesize, buffer = nil ) # -> buffer
.
.read_nonblock( bytesize, buffer = nil ) # -> buffer
, ,
. .
.
.readpartial( bytesize, buffer = nil ) # -> buffer
, ,
:

15.1. IO ()

176

;
;
;
. ,
EOFError.
, -
.
io.sysread, ,
, IOError. Errno::EWOULDBLOCK Errno::EINTR, (
NONBLOCK).

::readlines( path, sep = $/, options = nil ) # -> array


( path, size, options = nil ) # -> array
( path, sep, size, options = nil ) # -> array

(
). (
, /n/n).
.readlines( sep = $/, size = nil ) # -> array
.
.gets( sep = $/, bytesize = nil ) # -> string
(
). ( , /n/n).
, nil.
$_.
.readline( sep = $/, bytesize = nil ) # -> string
, .
.lineno # -> integer
( ) ($.).
.lineno=(pos) # -> integer
( )
. .
.seek( offset, object = IO::SEEK_SET ) # -> 0
( )
.

15.1. IO ()

177

-> _ = _ + offset
-> _ = _ + offset
IO::SEEK_SET -> _ = offset
IO::SEEK_CUR
IO::SEEK_END

.sysseek( offset, object = IO::SEEK_SET ) # -> 0


,
.
.rewind # -> 0
( ) . , , .

.getc # -> string


.
, nil.
.readchar # -> string
, .

.getbyte # -> integer


. , nil.
.readbyte # -> integer
, .
.pos # -> integer
: tell
( ) .
.pos=(pos) # -> integer
( )
. .

15.1. IO ()

178

::foreach( path, sep = $/, options = nil ) { |string| } # -> nil


( path, size, options = nil ) { |string| } # -> nil
( path, sep, size, options = nil ) { |string| } # -> nil

( IO::readlines).
.each( sep = $/ ) { |string| } # -> self
(size) { |string| } # -> self
( sep, size) { |string| } # -> self

: each_line, lines
( .readlines). Ruby lines .
.bytes { |byte| } # -> self
: each_byte
. Ruby bytes .
.chars { |char| } # -> self
: each_char
. Ruby chars .
.codepoints { |point| } # -> self
: each_codepoint
. Ruby codepoints .

15.1.4.
.
.to_s.
.

:
encoding: . ;
mode: . r ;
perm: ;
open_args: , .
::write( path, string, start = nil, options = nil ) # -> string.length
( - ).
.

179

15.1. IO ()

::binwrite( path, string, start = nil ) # -> string.length


rb:ASCII-8BIT.
.write(object) # -> object.to_s.bytesize
.
.syswrite(object) # -> object.to_s.bytesize
,
.
. object # -> io
.
.write_nonblock(string) # -> string.length
, , .
. . .
.print( *object = $_ ) # -> nil
.
$,, ,
nil, .
$\, , nil, .
.printf( format, *objects ) # -> nil
string

% [*object].

.putc(object) # -> object


. .
.puts( *object = $\ ) # -> nil
.
. .

, . , .

.

15.1. IO ()

180

.ungetbyte(object) # -> nil


( , io.sysread).
.ungetc(char) # -> nil
( , io.sysread).
.fdatasync # -> 0
.
.fsync # -> 0
.
.flush # -> 0
.
.sync=(bool) # -> bool
-
, .
.sync # -> bool
.

15.1.5.
.
. , .

:
STDIN ($stdin) - ().
.
STDOUT ($stdout, $>) - ().
;
STDERR ($stderr) - .
.

, . ,
,
.

15.1. IO ()

181


Kernel. .

Kernel.print

Kernel.printf

Kernel.putc

Kernel.puts

.display( io = $> ) # -> nil


. .
.p(*args) # -> args
(object.inspect) .
$/
.warn(message) # -> nil
.
.
Ruby
IO.puts. . .

,
kernel.gets kernel.readline.
.

.

15.1.6.
- , .
, , . Linux
.
.
. .
.

182

15.1. IO ()

: <process> | <processs> |
: mkfifo <name>
Ruby-.

<process>

::pipe( *encoding, options = nil ) # -> array


( *encoding, options = nil ) { |read, write| } # -> object

. ,
.
. .
rd, wr = IO.pipe
wr.puts "Text" # -> nil
rd.gets "Text" # -> "Text\n"

15.1.7.
,
, .
::select ( reads, writes = nil, errors = nil, sec = nil)
.
, , .
, . , , nil.

15.2. File ()

183

rp, wp = IO.pipe
mesg = "ping "
100.times {
rs, ws, = IO.select([rp], [wp])
if r = rs[0]
ret = r.read(5)
print ret
case ret
when /ping/
mesg = "pong\n"
when /pong/
mesg = "ping "
end
end
if w = ws[0]
w.write(mesg)
end
}
# ->
ping pong
ping pong
ping pong
(snipped)
ping

15.2. File ()
.
- Linux. Linux , .
. Linux .
File, IO,
, .
, , .
- .

:
File::SEPARATOR - , .
Windows (\), Linux - (/);

15.2. File ()

184

File::ALT_SEPARATOR - ;
File::PATH_SEPARATOR - , (:);
File::NULL - .
::new( name, mode, *perm ) # -> file
.
::open( name, mode, *perm ) # -> 0
( name, mode, *perm )

{ |file| } # -> object

, ,
.

15.2.1.
::delete(*path) # -> integer
: unlink
. .
::truncate( path, bytesize ) # -> 0
( ).
.truncate(bytesize) # -> 0
, .
::rename( path, new_name ) # -> 0
. .
::symlink( path, name ) # -> 0
.
::link( path, new_name ) # -> 0
.
.
::utime( atime, mtime, *path ) # -> integer
. .
::readlink(path) # -> filename
, .
.flock(constants) # -> 0
. .

15.2. File ()

185

- ( ). . ;
File::LOCK_EX

File::LOCK_NB - -

;
- ( ).

.
;
File::LOCK_SH

File::LOCK_UN

- .

15.2.2.
- ;
- (ruby 2.0).
File.dirname __FILE__.
__FILE__
__dir__

::path(object) # -> path


.to_path. .
.path # -> path
: to_path
( ).
::absolute_path( filename, basedir = File::pwd ) # -> path
. .
File.expand_path "test.rb", "~"
# -> "/home/krugloff/~/test.rb"
File.expand_path "/test.rb", ".rb" # -> "/test.rb"

::expand_path( filename, basedir = File::pwd ) # -> path


. .
File.expand_path "test.rb", "~" # -> "/home/krugloff/test.rb"
File.expand_path "/test.rb", ".rb" # -> "/test.rb"
File.expand_path('../config/environment', "my_app/config.ru")
# -> "/home/mak/my_app/config/environment"

::realdirpath( filename, basedir = File::pwd ) # -> path


. . . .
File.realdirpath "test.rb", "~" # -> error!
File.realdirpath "/test.rb", ".rb" # -> "/test.rb"

186

15.2. File ()

::realpath( filename, basedir = File::pwd ) # -> path


. . .
File.realpath "test.rb", "~" # -> error!
File.realpath "/test.rb", ".rb" # -> error!

::basename( path, extname = nil ) # -> filename


( ).
.
File.basename "/test.rb", ".rb" # -> "test"

::dirname(path) # -> basedir


( ).
File.dirname "/test.rb" # -> "/"

::split(path) # -> array


.
File.split "/test.rb" # -> [ "/", "test.rb" ]

::extname(path) # -> extname


.
.
File.extname "/test.rb" # -> ".rb"

::join(*name) # -> path


.
File::SEPARATOR.
File.join "/", "test", ".rb" # -> "/test/.rb"

::fnmatch?( pattern, path, constants = nil )


: fnmatch
.
File.fnmatch? 'cat', 'cat'

# -> true

File.fnmatch? 'cat', 'category' # -> false


File.fnmatch? 'c{at,ub}s', 'cats'

# -> false

File.fnmatch? 'c{at,ub}s', 'cats', File::FNM_EXTGLOB # -> true [Ruby 2.0]


File.fnmatch? 'c?t',

'cat'

# -> true

File.fnmatch? 'c??t',

'cat'

# -> false

File.fnmatch? 'c*',

'cats'

# -> true

File.fnmatch? 'c*t',

'c/a/b/t' # -> true

File.fnmatch? 'ca[a-z]', 'cat'

# -> true

File.fnmatch? 'ca[^t]',

# -> false

'cat'

187

15.2. File ()

File.fnmatch? 'cat', 'CAT'

# -> false

File.fnmatch? 'cat', 'CAT', File::FNM_CASEFOLD # -> true


File.fnmatch? '?',

'/', File::FNM_PATHNAME

# -> false

File.fnmatch? '*',

'/', File::FNM_PATHNAME

# -> false

File.fnmatch? '[/]', '/', File::FNM_PATHNAME

# -> false

File.fnmatch? '\?',

'?'

# -> true

File.fnmatch? '\a',

'a'

# -> true

File.fnmatch? '\a',

'\a', File::FNM_NOESCAPE

# -> true

File.fnmatch? '[\?]', '?'

# -> true

File.fnmatch? '*',

'.profile'

# -> false

File.fnmatch? '*',

'.profile', File::FNM_DOTMATCH

# -> true

File.fnmatch? '.*',

'.profile'

# -> true

rbfiles = '**/*.rb'
File.fnmatch? rbfiles, 'main.rb'

# -> false

File.fnmatch? rbfiles, './main.rb'

# -> false

File.fnmatch? rbfiles, 'lib/song.rb'

# -> true

File.fnmatch? '**.rb', 'main.rb'

# -> true

File.fnmatch? '**.rb', './main.rb'

# -> false

File.fnmatch? '**.rb', 'lib/song.rb'

# -> true

File.fnmatch? '*',

# -> true

'dave/.profile'

pattern = '*/*'
File.fnmatch? pattern, 'dave/.profile', File::FNM_PATHNAME

# -> false

File.fnmatch? pattern, 'dave/.profile',


File::FNM_PATHNAME | File::FNM_DOTMATCH
# -> true
pattern = '**/foo'
File.fnmatch? pattern, 'a/b/c/foo', File::FNM_PATHNAME

# -> true

File.fnmatch? pattern, '/a/b/c/foo', File::FNM_PATHNAME

# -> true

File.fnmatch? pattern, 'c:/a/b/c/foo', File::FNM_PATHNAME

# -> true

File.fnmatch? pattern, 'a/.b/c/foo', File::FNM_PATHNAME

# -> false

File.fnmatch? pattern, 'a/.b/c/foo',


File::FNM_PATHNAME | File::FNM_DOTMATCH
# -> true

::identical?( path, path2 )


.

15.2. File ()

188

15.2.3.

::chmod( *perm, *path ) # -> integer
. .
::lchmod( perm, *path ) # -> integer
,
, , .
::chown( user, group, *path ) # -> integer
. .
.
. . 0 -1 .
::lchown( user, group, *path ) # -> integer
, ,
, .
::umask( mask = nil ) # -> old_perm
, . ,
, .

::readable?(path)
.
::readable_real?(path)
.
::world_readable?(path)
(
).
::writable?(path)
.
::writable_real?(path)
.

15.2. File ()

189

::world_writable?(path)
(
).
::executable?(path)
.
::executable_real?(path)
.
::setuid?(path)
.
::setgid?(path)
.
::sticky?(path)
(sticky bit) .
::owned?(path)
( ).
::grpowned?(path)

(
).

15.2.4.
::stat(path) # -> a_file_stat
File::Stat, .
::lstat(path) # -> a_file_stat
, ,
, .
.lstat # -> file_stat
, .
::atime(path) # -> time
.
.atime # -> time
.

15.2. File ()

190

::ctime(path) # -> time


( ).
.ctime # -> time
(
).
::mtime(path) # -> time
.
.mtime # -> time
.
::size(path) # -> integer
.
.size # -> integer
.
::ftype(path) # -> string
.
file - ;
directory - ;
blockSpecial - ;
characterSpecial - ;
fifo - ;
link - ;
socket - ;
unknown - .

15.2.5.
::exist?(path)
: exists?
.
::size?(path) # -> integer
.
.
::zero?(path)
.
::file?(path)
.

15.3. Dir ()

191

::symlink?(path)
.
::directory?(path)
.
::blockdev?(path)
.
::chardev?(path)
.
::pipe?(path)
.
::socket?(path)
.

15.3. Dir ()
: Enumerable
- , -
.
- , ;
- , . ;
- , .
::new(path) # -> dir
.
::open(path) # -> dir
(path) { |dir| } # -> dir

, .
.
.close # -> nil
.
.

15.3. Dir ()

192

15.3.1.
::mkdir( name, *perm ) # -> 0
.
.
::delete(path) # -> 0
: rmdir, unlink
. , ,
.
::chdir( path = Dir.home ) # -> 0
( path = Dir.home ) { |path| } # -> object

, .
::chroot(path) # -> 0
Unix- .
, ,
, . .

15.3.2.
::entries(path) # -> array
, .
::glob( pattern, constants = nil ) # -> array
( pattern, constants = nil ) { |name| } # -> nil

( ).
. . ,
.
::[pattern] # -> array
Dir.glob

pattern, 0.

.read # -> name


. nil.
.pos # -> integer : tell
.
.seek(pos) # -> self
.
.pos=(pos) # -> integer
.

15.4.

193

.rewind # -> self


.

15.3.3.
.each { |name| } # -> self
.
::foreach(path) { |name| } # -> nil
.

15.3.4.
::directory?(path)
: exist?, exists?
,
.
::getwd # -> path
: pwd
.
::home( user = nil ) # -> path
.
.inspect # -> string
.
.path # -> path
( ).

15.4.
.test( type, first_path, second_path = nil )
.

15.4.

194

:
?A - ;
?C - ;
?M - ;
?e - ;
?s - . nil;
?z - ;
?f - ;
?L - ;
?d - ;
?b - ;
?c - ;
?S - ;
?p - ;
?r - ;
?R - ;
?w - ;
?W - ;
?x - ;
?X - ;
?u - ;
?g - ;
?K - (sticky bit) ;
?o -
( );
?O - ( );
?G - ( );
?- - ;
?= - ;
?< - ;
?> - .

15.4.1. File::Stat
file.stat file.lstat.
,
.

15.4.

195

::new(path) # -> stat


.
.

.inspect # -> string
.

.<=>(stat)
.

, File.

.readable?
.readable_real?
.world_readable?
.writable?
.writable_real?
.world_writable?
.executable?
.executable_real?
.setuid?
.setgid?
.sticky?
.owned?
.grpowned?

.uid # -> integer


.
.gid # -> integer
.
.mode # -> perm
.

15.4.

196

,
File.

.atime
.ctime
.mtime
.size
.ftype

.blksize # -> integer


, . , nil.
.blocks # -> integer
, . , nil.
.dev # -> integer
, .
.dev_major # -> integer
.
.dev_minor # -> integer
.
.rdev # -> integer
, .
.rdev_major # -> integer
.
.rdev_minor # -> integer
.
.ino # -> integer
Inode .
.
.nlink # -> integer
.

15.4.

197

, File.

.zero?
.file?
.symlink?
.directory?
.blockdev?
.chardev?
.pipe?
.socket?

15.4.2. FileTest

,
File.

FileTest::readable?(path)
FileTest::readable_real?(path)
FileTest::world_readable?(path)
FileTest::writable?(path)
FileTest::writable_real?(path)
FileTest::world_writable?(path)
FileTest::executable?(path)
FileTest::executable_real?(path)
FileTest::setuid?(path)
FileTest::setgid?(path)
FileTest::sticky?(path)
FileTest::owned?(path)
FileTest::grpowned?(path)

, File.

FileTest::exist?(path)

(: exists?)

FileTest::size?(path) # -> integer


FileTest::zero?(path)
FileTest::file?(path)
FileTest::symlink?(path)
FileTest::directory?(path)
FileTest::blockdev?(path)
FileTest::chardev?(path)
FileTest::pipe?(path)
FileTest::socket?(path)

15.4.

, File.

FileTest::size(path) # -> integer


FileTest::identical?( first_path, second_path )

198

16


, ,
ARGV.

16.1.
, , ,
. ARGV,
- ARGF.

16.1.1. ARGV
, , kernel.gets kernel.readline. .

16.1.2. ARGF
: Enumerable
ARGF ($<) - , , ARGV.
, ARGV .
, ARGV
(, ).
.
.
, .
ARGV , ARGF
.

. .

ARGF::binmode

ARGF::close

ARGF::skip

ARGF::binmode?

( IOError)

( )

16.1.

ARGF::closed?

ARGF::eof?

200

(: eof)

::argv # -> ARGV


::filename # -> path
: path
.
"-".
$FILENAME.

. .

ARGF::external_encoding

ARGF::internal_encoding

ARGF::set_encoding


::to_s # -> ARGF
::to_io # -> io
: file
( ).
::to_i # -> integer
: fileno
. ArgumentError.
::to_a( sep = $/, size = nil ) # -> array
: readlines
( ). ( ,
\n\n).
::to_write_io # -> io
, ( -
-i).

16.1.

201


. .
:

ARGF::read

ARGF::read_nonblock

ARGF::readpartial

:
+ ARGF::gets
+ ARGF::readline
+ ARGF::lineno
+ ARGF::lineno=(pos)
+ ARGF::seek
+ ARGF::rewind
:

ARGF::getc

ARGF::readchar

ARGF::getbyte

ARGF::readbyte

ARGF::pos

ARGF::pos=(pos)

(: tell)

ARGF::each

(: each_line,

ARGF::bytes

(: each_byte)

ARGF::chars

(: each_char)

ARGF::codepoints

lines)

(: each_codepoint, Ruby 2.0)

16.1.

202


ARGF
-i.
. . .
::inplace_mode # -> string
, .
::inplace_mode=(ext) # -> self
, .

ARGF::write

ARGF::print

ARGF::printf

ARGF::putc

ARGF::puts

17


, , . - , (
).

17.1.
.
,
. .
,
$LOAD_PATH ($:) ( Ruby 2.0; String
object.to_path). , (
).
.require(path) # -> bool
.
$LOAD_FEAUTURES ($) ( Ruby 2.0; String
object.to_path).
. 0.
,
.
. .rb. , (,
.so .dll).
.require_relative(path) # -> bool
, .
.load( path, anonym = false )
.
.

17.2. (Ruby 2.0)

204

. .
.autoload( name, path ) # -> nil
( ).
.
.autoload?(name) # -> path
, . , nil.
module.autoload module.autoload?.

17.2. (Ruby 2.0)


Ruby , , . - , . , .
.
:
.
:
.
.
.
.refine(a_class) { } # -> a_module [private Module]
.
, (self ). .
( ).
,
.
#
class String
def bang
"#{self}"
end
end
"Hello".bang # -> "Hello"

17.2. (Ruby 2.0)

205

#
module StringBang
"Hello".bang # -> NoMethodError!
refine String do
def bang; "#{self}"; end
end
"Hello".bang # -> "Hello!"
end
"Hello".bang # -> NoMethodError!

.using(module) # -> main [MAIN]


. Kernel.eval, Kernel.instance_eval
Kernel.module_eval.
, .
,
(
super).
module Foo
def foo
puts "C#foo in Foo"
end
end
class C
prepend Foo
def foo
puts "C#foo"
end
end
class D < C
def foo
super
end
end

17.2. (Ruby 2.0)

206

module M
refine C do
def foo
puts "C#foo in M"
end
end
end
C.new.foo # -> 'C#foo in Foo'
using M
C.new.foo # -> "C#foo in M"
D.new.foo # -> "C#foo in Foo"
class E < C
def foo
super
end
end
E.new.foo # -> "C#foo in M"

, . Kernel.send,
Kernel.method, Kernel.respond_to?.
C = Class.new
module M
refine C do
def foo
puts "C#foo in M"
end
end
end
def call_foo(x)
x.foo
end
using M
x = C.new
x.foo

# -> "C#foo in M"

x.send :foo # -> NoMethodError!


x.respond_to? :foo # -> false
call_foo(x) # -> NoMethodError!

17.2. (Ruby 2.0)

207

, , .
# c.rb:
class C
end
# m.rb:
require "c"
module M
refine C do
def foo
puts "C#foo in M"
end
end
end
# m_user.rb:
require "m"
using M
class MUser
def call_foo(x)
x.foo
end
end
# main.rb:
require "m_user"
x = C.new
m_user = MUser.new
m_user.call_foo(x)

# -> C#foo in M

x.foo

# -> NoMethodError!

, .using .

17.2. (Ruby 2.0)

208

# :
# not activated here
using M
# activated here
class Foo
# activated here
def foo
# activated here
end
# activated here
end
# activated here
# eval:
# not activated here
eval <<EOF
# not activated here
using M
# activated here
EOF
# not activated here
# :
# not activated here
if false
using M
end
# not activated here

, ,
.

18

- ,
, , . ,
.
Exception .
, .

StandartError RuntimeError.
, ,
. Errno Exception.
SystemCallError,
Errno.
Errno (Errno::<ErrorKlass>::Errno).

18.1.
Exception - .
NoMemoryError - ;
ScriptError- ;
* LoadError - ;
NotImplemenetedError - ;
SyntaxError - ;
SecuirityError - ;
SignalException - ;
* Interrupt - ( Ctrl+C);
SystemExit - ;
SystemStackError - ;
StandardError - ;
* Math::DomainError - ;
ArgumentError - ;
EncodingError - , ;

18.2.

210

Encoding::CompatibilityError - ;
Encoding::ConverterNotFoundError -
;
Encoding::InvalidByteSequenceError - ;
Encoding::UndefinedConversionError - ;
FiberError - ;
IOError - ;
EOFError - ;
IndexError - ;
KeyError - ;
StopIteration - ;
LocalJumpError - ;
NameError - ;
NoMethodError - ;
RangeError - ;
FloatDomainError -
(NaN ..);
RegexpError - ;
RuntimeError - ;
SystemCallError - ;
ThreadError - ;
TypeError - .
;
ZeroDivisionError - .

18.2.
18.2.1. Exception
::exception( message = nil ) # -> exception
.
object.to_str.

::new( mesage = nil ) # -> exception


.
.exception( message = nil ) # -> exception
.
.to_str.

18.2.

211

.backtrace # -> array


.
:
"_:_: in '_'"

"_:_"

.set_backtrace(array) # -> array


.
.to_s # -> string
: message
( ).
.inspect # -> string .

18.2.2. LoadError [ruby 2.0]


.path # -> string
, .

18.2.3. SignalException
::new(sig_name) # -> a_signal_exception
(sig_number, name = nil)

.
.
.signo # -> number
.

18.2.4. SystemExit
::new( status = 0 ) # -> exception
.
.status # -> integer .
.success? # -> bool
.

18.2.

212

18.2.5. Encoding::InvalidByteSequenceError
.destination_encoding # -> encoding
.destination_encoding_name # -> string .
.source_encoding # -> encoding
. .
.source_encoding_name # -> string
.
.
.error_bytes # -> string
- .
.incomplete_input? # -> bool
-
.
.readagain_bytes # -> string
, .

18.2.6. Encoding::UndefinedConversionError
.destination_encoding # -> encoding
.destination_encoding_name # -> string .
.source_encoding # -> encoding
. .
.source_encoding_name # -> string
.
.
.error_char # -> string
- .

18.2.7. StopIteration
.result # -> object .

18.3.

213

18.2.8. LocalJumpError
.exit_value # -> object
, .
.reason # -> symbol
,
(:break, :redo, :retry, :next, :return, :noreason).

18.2.9. NameError
::new( message, name = nil ) # -> exception
.
.name # -> name
, .

18.2.10. NoMethodError
::new( message, name, *args ) # -> exception
.
.args # -> object
, .

18.2.11. SystemCallError
::new( message, integer ) # -> exception
Errno ( )
SystemCallError.
.errno # -> integer .

18.3.
18.3.1.

Kernel.
.raise( message = nil ) # -> exception
( exc = RuntimeError, message = nil, pos = caller ) # -> exception

: fail

18.3.

214


( RuntimeError), $! nil.
, .exception, .

18.3.2.
rescue, begin, def, class, module.
, .
, .
,
.
.

begin
_
rescue
_
else
code
ensure
code
end


. $!
.

rescue => _.
StandardError .
rescue class rescue class => _.
.
else . , .
ensure .
( return, break .)

18.3.

215

:
rescue _

, . StandardError .

18.3.3. Catch Throw



catch throw. Ruby
Kernel, .
.catch(name = nil) { |name| } # -> object
. object.throw . .
.throw( name, *args )
, object.catch
( ). c . object.catch.

19


19.1.
, , .

19.1.1.
, ,
. -
.
.
- .
. - . ,
.
, , , .
, , , .
,
- .
:
- (unit test);
- ;
- , ;
-
.
.
, .

19.2.

217

testrb ( Ruby, Test::Unit).


(
) .

irb.

19.1.2. TDD
- ,
(TDD, Test-Drive Development). :
, ;
. ( );
;
. .
(.. ).
-> -> ->
().

19.2.
19.2.1.
, .
.global_variables # -> array [PRIVATE: Kernel]
.
.local_variables # -> array [PRIVATE: Kernel]
.
::constants # -> array [Module]
( Object).
::nesting # -> array [Module]
.
.__method__ # -> symbol [Kernel]
: __callee__
. nil.
Ruby ,
.

19.2.

218

def first; __callee__; end


first # -> :first
alias second first
second # -> :first


RUBY_PATCHLEVEL - ;
RUBY_PLATFORM - ;
RUBY_RELEASE_DATE - ;
RUBY_VERSION - ;
$PROGRAM_NAME ($0) - ( );
__dir__ - (ruby 2.0).
File.dirname __FILE__;
__FILE__ - ;
__LINE__ - ;
__Encoding__ - .

19.2.2.
.caller( offset = 1 ) # -> array [Kernel]
, :
":_" ": _ in ".
Ruby .
, , nil.
Ruby 2.0

.
.caller_locations( start = 1, length = nil ) # -> array or nil [Ruby 2.0]
(range) # -> array or nil

, Thread::Backtrace::Location.
, nil.

19.2.

219

# Ruby 1.9:
def whoze_there_using_caller
caller[0][/`([^']*)'/, 1]
end
# Ruby 2.0:
def whoze_there_using_locations
caller_locations(1, 1)[0].label
end

Thread::Backtrace::Location
.absolute_path # -> string
.
caller_locations.last.absolute_path # -> "/usr/bin/irb"

.base_label # -> string


.
.
caller_locations.last.base_label # -> "main"

.inspect # -> string


.
caller_locations.last.inspect # -> "\"/usr/bin/irb:12:in '<main>'\""

.label # -> string


. , , .. .
caller_locations.last.label # -> "<main>"

.lineno # -> integer


.
caller_locations.last.lineno # -> 12

.path # -> string


.
loc = caller_locations(0..1).first
loc.path # -> 'caller_locations.rb'

.to_s # -> string


Kernel.caller.
caller_locations.last.to_s # -> "/usr/bin/irb:12:in '<main>'"

19.2.

220

19.2.3.
Kernel.
.set_trace_func( proc = nil )

. .
: , , , , Binding .
nil .
:
c-call - ;
c-return - ;
call - Ruby ;
return - Ruby ;
class - ;
end - ;
line - ;
raise - .
Ruby. TracePoint.
.trace_var( name, code ) # -> nil
(name) { |object| } -> nil

.
.
.untrace_var( name, code = nil ) # -> array
. , .
TracePoint (ruby 2.0)
Kernel.set_trace_func .
.

::new(*events) { |a_trace_point| } # -> a_trace_point
.
.
.
:

19.2.

221

line: ;
class: ;
end: ;
call: ;
return: ;
c_call: ;
c_return: ;
raise: ;
b_call: ;
b_return: ;
thread_begin: ;
thread_end: .
trace = TracePoint.new(:call) do |tp|
p [tp.lineno, tp.defined_class, tp.method_id, tp.event]
end
# -> #<TracePoint:0x007f17372cdb20>

ThreadError.
, , RuntimeError.
TracePoint.trace(:line) do |tp|
p tp.raised_exception
end
# -> RuntimeError!

RuntimeError.
TracePoint.trace(:line) do |tp|
$tp = tp
end
$tp.line # -> RuntimeError!

::trace(*events) { |a_trace_point| } # -> a_trace_point


, .

.enable # -> boolean
{ } # -> self

. false.
trace.enabled?

# -> false

trace.enable

# -> false

trace.enabled?

# -> true

trace.enable

# -> true

19.2.

222

, .
trace.enabled? # -> false
trace.enable do
trace.enabled?
end
trace.enabled? # -> false

.disable # -> boolean


{ } # -> self

. false.
trace.enabled? # -> true
trace.disable

# -> false

trace.enabled? # -> false


trace.disable

# -> false

,
.
trace.enabled? # -> true
trace.disable do
trace.enabled?
end
trace.enabled? # -> true

.enabled? # -> boolean


.

.binding # -> a_binding


.
.defined_class # -> a_module
(
), .
.

19.2.

223

class C; def foo; end; end


trace = TracePoint.new(:call) do |tp|
p tp.defined_class # -> C
end.enable do
C.new.foo
end
module M; def foo; end; end
class C; include M; end;
trace = TracePoint.new(:call) do |tp|
p tp.defined_class # -> M
end.enable do
C.new.foo
end
class C; def self.foo; end; end
trace = TracePoint.new(:call) do |tp|
p tp.defined_class # -> #<Class:C>
end.enable do
C.foo
end

.event # -> symbol


.
.inspect # -> string
.
.lineno # -> integer
.
.method_id # -> string
.
.path # -> string
.
.raised_exception # -> an_exception

( :raise).
.return_value # -> object
( :return, :c_return, :b_return).
.self # -> a_trace_point
, .

20


20.1.
Ruby
. .

20.1.1.
- . ( ).
,
. .
- . . ,
.
. ,
.
(thread) (io). - (, , ..), -
, .
,
() ( ), .
,
.
, ;
;
.
, - .

20.1.

225

.
.
,
, , . , ( ,
).

20.1.2.
Ruby ,
(GIL), . GIL , .
- ,
. .
, .
, Ruby
( ).
Ruby .
, . , , , .
. ( ). - ,
.

20.1.3.
, . -
.
.

, , ,
.

20.2. (Thread)

226

register = i
register = register + 1
i = register

,
, .

20.1.4.
Ruby
. .
: ;
(STM): ,
, (Clojure);
: ,
. ,
(Scala,
Erlang).

20.2. (Thread)
, -
, .
: , . , ,
,
.
Edward A. Lee
, , , , - .
, , .
,
, .
,
, , , .
( ), , , .

20.2. (Thread)

227

Ruby
(, , ).
-
.
:
- , ;
- , ( , );
- , .
, .
. .
. ( /).

20.2.1. Thread
Thread POSIX .
::start(*arg) { |*arg| } # -> thread
: fork, new
.
Thread.start { } # -> #<Thread:0x962817c run>

::list # -> array


, .
Thread.list # -> [#<Thread:0x94da0a4 run>, #<Thread:0x964b4d8 sleep>!

::current # -> thread


.
Thread.current # -> #<Thread:0x94da0a4 run>

::main # -> thread


.
Thread.main # -> #<Thread:0x94da0a4 run>


::pass # -> nil
. (.. ).
Thread.start { Thread.pass } # -> #<Thread:0x962e554 run>

20.2. (Thread)

228

::stop # -> nil


.
::exit # -> thread
C: kill
. , Thread.

.join( sec = nil ) # -> thread

, (
-
nil).
a = Thread.new { print ?a; sleep(10); print ?b; print ?c }
x = Thread.new { print ?x; Thread.pass; print ?y; print ?z }
x.join
# -> "axyz"
y = Thread.new { 4.times { sleep 0.1; puts 'tick... ' } }
puts "Waiting" until y.join 0.15
# ->
"tick...
Waiting
tick...
Waiting
tick...
tick..."

Ruby
ThreadError.
.value # -> object
( .join).
.run # -> self
. ,
, .
.wakeup # -> self
(
).

20.2. (Thread)

229

.exit(status) # -> self


: kill, terminate
. , Thread.
.priority # -> integer
. . , .
, .
.
.priority=(integer) # -> self
.
.add_trace_func( proc = nil ) # -> proc
: set_trace_func
. nil, .

.[name]=(object) # -> object
.
, (
).
[
Thread.new { Thread.current["name"] = "A" },
Thread.new { Thread.current[:name]

= "B" },

Thread.new { Thread.current["name"] = "C" }


].each do |th|
th.join
puts "#{th.inspect}: #{th[:name]}"
end
# ->
#<Thread:0x00000002a54220 dead>: A
#<Thread:0x00000002a541a8 dead>: B
#<Thread:0x00000002a54130 dead>: C
Thread.main[:local] = 4 # -> 4

20.2. (Thread)

230

.[name] # -> object


. , nil.
Thread.main[:local] # -> 4

.keys # -> array


.
Thread.main.keys # -> [:local]

.key?(name)
.
Thread.main.key? :global # -> false

Ruby 2.0
Ruby . .[],
.
.thread_variable_set(name, value)
.
.thread_variable_get(name) # -> value
.
Thread.new {
Thread.current.thread_variable_set("foo", "bar")
Thread.current["foo"] = "bar"
Fiber.new {
Fiber.yield [
Thread.current.thread_variable_get("foo"), # -> 'bar'
Thread.current["foo"],

# -> nil

]
}.resume
}.join.value # -> ['bar', nil]

.thread_variable?(name) # -> bool


.
me = Thread.current
me.thread_variable_set(:oliver, "a")
me.thread_variable?(:oliver)

# -> true

me.thread_variable?(:stanley)

# -> false

20.2. (Thread)

231

.thread_variables # -> array


.
thr = Thread.new do
Thread.current.thread_variable_set(:cat, 'meow')
Thread.current.thread_variable_set("dog", 'woof')
end
thr.join

# -> #<Thread:0x401b3f10 dead>

thr.thread_variables

# -> [:dog, :cat]


::abort_on_exception # -> bool
. - false.
::abort_on_exception=(bool) # -> bool
.
, .
$DEBUG true ( -d).
Thread.main.exit(0).
.abort_on_exception # -> bool
. - false.
.abort_on_exception= (bool) # -> bool
.
, .
$DEBUG true ( -d).
.raise( message = nil )
( exc, message = nil, pos = nil )

. .
[ruby 2.0]
Ruby . (.raise), (.kill) (
).

20.2. (Thread)

232

::handle_interrupt(options) { } # -> result


(
). , .
.

:
:immediate - ;
:on_blocking - ;
:never - .
# `RuntimeError` .
th = Thread.new do
Thread.handle_interrupt(RuntimeError => :never) {
begin
# You can write resource allocation code safely.
Thread.handle_interrupt(RuntimeError => :immediate) {
# ...
}
ensure
# You can write resource deallocation code safely.
end
}
end
Thread.pass
# ...
th.raise "stop"

::pending_interrupt?(exception_klass = nil) # -> boolean



( ). , .

20.2. (Thread)

233

th = Thread.new{
Thread.handle_interrupt(RuntimeError => :on_blocking){
loop do
# ...
# ( ).
if Thread.pending_interrupt?
Thread.handle_interrupt(Object => :immediate){}
end
# ...
end
}
}
# ...
th.raise # .

.pending_interrupt?(exception_klass = nil) # -> boolean


.

.group # -> thgroup


, .
, nil.
Thread.main.group # -> #<ThreadGroup:0x94d9d98>

.inspect # -> string


.
Thread.main.inspect -> "#<Thread:0x94da0a4 run>"

.status # -> object


.
run - ;
sleep - ;
false - ;
nil - ;
aborting - ;
Thread.main.status -> "run"

.alive? # -> bool


( ).
Thread.main.alive? -> true

.stop? # -> bool


( ).
Thread.main.stop? -> false

20.2. (Thread)

234

.safe_level # -> integer


.
Thread.main.safe_level -> 0

.backtrace # -> array


.
.backtrace_locations(*args) # -> array || nil [Ruby 2.0]
. .caller_locations.

20.2.2. (ThreadGroup)
- . . ,
. ,
.
::Default # -> thgroup
, . .
::new # -> thgroup
.
ThreadGroup.new # -> #<ThreadGroup:0x9711728>

.add(thread) # -> thgroup


.
Thread.main.group # -> #<ThreadGroup:0x94d9d98>
ThreadGroup.new.add Thread.main # -> #<ThreadGroup:0x96f0154>
Thread.main.group # -> #<ThreadGroup:0x96f0154>

.enclose # -> thgroup


, .
Thread.main.group.enclose # -> #<ThreadGroup:0x96f0154>
ThreadGroup.new.add Thread.main # -> error

.enclosed? # -> bool


.
Thread.main.group.enclosed? # -> true

.list # -> array


, .
Thread.main # -> #<Thread:0x94da0a4 run>
Thread.main.group.list # -> [#<Thread:0x94da0a4 run>]

20.2. (Thread)

235

20.2.3. (Mutex)
, ( ).
: . , Ruby, (Mutex - mutual exclusion, ). , .

. , Matz
.
, , Mutex. , .
.
::new # -> mutex
.
.lock # -> mutex
. , ThreadError.
Ruby (.trap) ThreadError.
.try_lock # -> bool
. .
Ruby (.trap) ThreadError.
.synchronize # -> bool
.
@mutex = Mutex.new
@mutex.synchronize do
i += 1
end

Ruby (.trap) ThreadError.


.locked? # -> bool
.
.owned? # -> bool [Ruby 2.0]
?

20.3. (Process)

236

.unlock # -> mutex


. , ThreadError.
Ruby (.trap) ThreadError.
.sleep( sec = nil ) # -> sec
. ,
ThreadError.
Ruby (.trap) ThreadError.
( ).

20.3. (Process)
20.3.1. Linux
, , , .
init
.
, ( / ).
( ) .
- , .
:
PID - ;
PPID - ;
UID - ( , );
EUID - .
;
GUID - ;
EGUID - . , ;

20.3. (Process)

237

;
;
.
:
();
;
();
- .
- .

20.3.2.
- , .
:
ps

: kill -15 PID kill -TERM PID


: kill -9 kill -KILL
:
: nice -5 NAME ( 10);
: nice 7 NAME;
: renice 7 PID
,
, ,
.

20.3.3. Ruby
- . Ruby , .

, .
.fork { nil } # -> status
, , , .
PID ;
PPID PID ;

20.4. (Signal)

238

, . .

exec, . .
Linux , .
.
.
. 0.
, :
;
nil.

::wait ::detach, .
,
Process.respond_to?(:fork) false.
.fork { nil } # -> status [PRIVATE: Kernel]
Kernel.

20.4. (Signal)
- .
::list # -> hash
, .
::trap( name, command ) # -> object
(name) { } # -> object

.
( SIG ), . .
Ruby :SEGV, :BUS, :ILL, :FPE, :VTALRM
ArgumentError.

20.5.

239

command:
, ;
:

- ;
"DEFAULT" ("SIG_DFL") - ;
"SYSTEM_DEFAULT" - ;
"EXIT" (0) - .
"IGNORE" ("SIG_IGN")

- : Unix - "/bin/sh", Windows - ENV["RUBYSHELL"]


ENV["COMSPEC"];
string, *arg - ;
{ [string, first_arg], *arg } - ,
.
string

.trap( name, command ) # -> object [PRIVATE: Kernel]


(name) { } # -> object

Kernel.
::signame(signo) # -> string [Ruby 2.0]
.
Signal.trap("INT") { |signo| puts Signal.signame(signo) }
Process.kill "INT", 0
# -> 'INT'

20.5.
, IO .
IO.
, .
IO . IO .
Goliath Thin.
. / (
).

20.6. C

240

20.6. C
, , .
RArray, RHash, RFile ..
,
. - RValue.
RValue , . .
, .
:
;
(
).
. , ( ).
:
-
FL_MARK. ;
.
. . ( )
. ,
( 10 ).
,
.
( ). .
. ,
, ,
.

20.6.1. Ruby 2.0


Bitmap marking ( ). ( -, ).

20.6. C

241

ree (ruby enterprise edition).


, ,
. , . 1
FL_MARK.
( ), .

( ), . , .
,
.
, , ,
. malloc() posix_memalign().

21

- Ruby.
Ruby
,
.
:
, ( ARGV);
( ENV);
, , ;
, .
. .
-T
( - 0).
SecurityError.
$SAFE

21.1.
.

21.1.1. 0
.

21.1.2. 1
:
, ;
, ;
, ;
, ;
-e,

-i, -l, -r, -s, -S, -X;

21.1.

243

Dir, IO, File, FileTest, ;


test, eval, require, load, trap, .
RUBYLIB RUBYOPT .

21.1.3. 2

fork

syscall

exit!

Process.equid=

Process.fork

Process.setpgid

Process.setsid

Process.kill

Process.seeprioprity

21.1.4. 3
, . .untaint .

21.1.5. 4
:
;
require load ( );
;
;
;
;
;
.srand Random.srand.
.eval, .

21.2.

244

21.2.
.
.freeze # -> self
.
.frozen? # -> bool
.
.taint # -> self
.
.
.untaint # -> self
.
.tainted? # -> bool
.
.untrust # -> self
, .
,
4.
.trust # -> self
, .
.untrusted? # -> bool
.

:
--copyright - ;
--version - ;
-(-h)elp - ;
-0 [codepoint] - ,
($/). .
, ;
-00,
;
-0777, .
-C (-X) <dir> - ;
--encoding (-E) <external>[:internal] - ;
-F <pattern> - ($;),
.split.
;
-I <dirs> - . $LOAD_PATH ($:) . (Linux)
(Windows);
-K <encoding> - .
e - EUC-JP;
s - Windows-31J (CP932);
u - UTF-8;
n - ASCII-8BIT (BINARY).
-S - PATH;
-T [security] - (
1);
-U - UTF-8 ;
-W [verbose] - :

A.

247

0 - , $VERBOSE nil;
1 - , $VERBOSE false;
2 ( ) - , $VERBOSE
true.
-a - -n
-p. : $F = $_.split!;
-c - . ,
"Syntax OK";
-(-d)ebug - ($DEBUG true).
,
$DEBUG true;
{verbatim} if $DEBUG

-e <verbatim> - ;
-i [ext] - ,
ARGF. ;
-l - . , -, $\ $/, ,
-, .chop!;
-n - ( ):
while gets
# code
end

-p - (
, ):
while gets
# code
end
print

-r <lib> - .require;
-s - , . --. ARGV.
-x=y, $x y;
-x, $x true.
-(-v)erbose - -w. ,
.

A.

248

,
$VERBOSE true;
{verbatim} if $VERBOSE

-w - ($VERBOSE
true);
-x [dir] - , !# ruby. EOF (
), ^D (control-D), ^Z (control-Z), __END__. ;
-(-y)ydebug - ;
--disable-... (--enable-...) - :
gems - (
);
rubyopt - RUBYOPT;
all - .
--dump <target> - .

:
RUBYLIB - , ;
RUBYOPT - , .
-d, -E, -I, -K, -r, -T, -U, -v, -w, -W, --debug, -disable-... --enable-...;
RUBYPATH - , ;
RUBYSHELL - .
mswin32, mingw32, OS/2;
PATH - .
ENV - , . .to_hash,
.

:
$F - $_.split.
, -a, -n -p;
$-W - ;
$-i - , ;
$-d # -> bool ;
$-l # -> bool ;

A.

249

$-v # -> bool ;


$-p # -> bool ;
$-a # -> bool ;
$* - , ;
$> - ;
$; ($-F) - string.split.
( nil);
$/ ($-0) - kernel.gets. (
- "\n"). nil, ;
$\ - , (
nil);
$, - array.join kernel.printf
( nil);
$~ - MatchData ;
$& - ;
$ - , ;
$ - , ;
$+ - ;
$1, $2, $3, $4, $5, $6, $7, $8, $9 - ,
;
$LOAD_FEAUTURES ($) - ( Ruby 2.0;
String object.to_path);
$LOAD_PATH ($:, $-I) - , ( Ruby 2.0;
String object.to_path);
$. - ;
$_ - ;
$! - ;
$@ - ;
$DEBUG - true, -(-d)ebug;
$VERBOSE ($-v, $-w)
nil, -W0;
true, -w -(-v)erbose;
false .
$$ - ;
$? - ;
$FILENAME - ARGF. "-";
$SAFE - .


Ruby
Onigmo: http://github.com/k-takata/Onigmo.

http://perldoc.perl.org/perlre.html.

:
i ;
m . ;
x (, , )
;
o
, ;
u, e, s, n
. : u - UTF-8, e - EUC-JP , s - Windows-31J , n - ASCII8BIT.

ASCII :
. - (
);
\w - , ;
\W - , , ;
\s - (, ,
);
\S - , ;
\d - ;
\D - , ;
\h - ;
\H - , .

B.

251

Unicode :
\R - Ruby ,
. non really.
(?>\x0D\x0A|[\x0A-\x0D\x{85}\x{2028}\x{2029}]) Unicode
(?>\x0D\x0A|[\x0A-\x0D]) .

"\n" =~ /^\R$/

# -> 0

"\r" =~ /^\R$/

# -> 0

"\r\n" =~ /^\R$/ # -> 0

\X - Ruby Unicode. eXtended


Unicode character.
"P\u{307}" =~ /^\X$/ # -> 0

[[::]] - , :

alnum - ;
alpha - ;
ascii - ASCII ;
blank - ;
cntrl - ;
digit - ;
graph - , ;
lower - ;
print - , , ;
punct - ;
space - (, , );
upper - ;
word - , ( );
xdigit - ;

\p{} - , .
\p{^} - , .

B.

252

Alnum - ;
Alpha - ;
Any - Unicode ;
ASCII - ASCII ;
Assigned - ;
Blank - ;
Cntrl - ;
Digit - ;
Graph - , ;
Lower - ;
Print - , , ;
Punct - ;
Space - (, , );
Upper - ;
Word - , ( );
Xdigit - .

Unicode- :
C - ; Cc - ; Cf - ,
; n - ; Co - ; Cs -;
L - ; Ll - ; Lm - ; Lo - ; Lt - ; Lu - ;
M , ; Mn - , ; Mc - ,
; Me - ,
;
N - ; Nd - ; Nl - ; No -
;
P - ; Pc - ; Pd - ; Ps - ; Pe - ; Pi -
; Pf - ; Po - ;
S - ; Sm - ; Sc -
; Sk - ; So -
;
Z - , ; Zs - ;
Zl - ; Zp - .
, .
: Arabic, Armenian, Balinese, Bengali, Bopomofo, Braille, Buginese,
Buhid, Canadian_Aboriginal, Carian, Cham, Cherokee, Common, Coptic, Cuneiform,

B.

253

Cypriot, Cyrillic, Deseret, Devanagari, Ethiopic, Georgian, Glagolitic, Gothic, Greek,


Gujarati, Gurmukhi, Han, Hangul, Hanunoo, Hebrew, Hiragana, Inherited, Kannada,
Katakana, Kayah_Li, Kharoshthi, Khmer, Lao, Latin, Lepcha, Limbu, Linear_B,
Lycian, Lydian, Malayalam, Mongolian, Myanmar, New_Tai_Lue, Nko, Ogham,
Ol_Chiki, Old_Italic, Old_Persian, Oriya, Osmanya, Phags_Pa, Phoenician, Rejang,
Runic, Saurashtra, Shavian, Sinhala, Sundanese, Syloti_Nagri, Syriac, Tagalog,
Tagbanwa, Tai_Le, Tamil, Telugu, Thaana, Thai, Tibetan, Tifinagh, Ugaritic, Vai, and
Yi.

:
[...] - .
(a-z);
[^...] - ,
;
(?:...) -
;
(...) -
. ( 1 9);
(?<>...) -
. .
, , ,
, nil, .
.
$1 $9
, .

:
\_ - , ;
\K <> - ,
;
\g <...> - ,
. Ruby (. Onigmo).

B.

254

:
...? - 0 1 ;
...* - 0 .
( );
...*? - 0 .
( );
...+ - 1 .
( );
...+? - 1 .
( );
...{a, b} - a b .
( );
...{a, b}? - a b .
( ).
a, b, .

:
^... - ;
...$ - ;
\A... - ;
...\z - ;
...\Z -
, ;
...\b - ;
\b... - ;
...\B - , ;
\B... - , .
/^...$/
. , , /\A...\z/.
\b...\b .

:
1|2 - ;
1&&2 - ;
1(?=2) - 1, 2 ( );

B.

255

1(?!2) - 1, 2
( );
1(?<=2) - 1, 2
( );
\K - Ruby , ( ).
(/1 \K 2/ /(?<=1) 2/).
keep.
1(?<!2) - 1, 2
( ).
(?(cond)yes|no) - Ruby .
/.
regexp = /^([A-Z])?[a-z]+(?(1)[A-Z]|[a-z])$/
regexp =~ "foo"

# -> 0

regexp =~ "foO"

# -> nil

regexp =~ "FoO"

# -> 0

:
(?#...) - ;
(?>...) - ;
(?1-2) - 1 2
;
(?1-2:...) - 1 2
.


- , .
, .
.
.
( , ):
%[][][.]< >

.
.
"%5d"%2 # -> "

2"

(
- 6).

:
:
b - .
2 .. .
"%b" % 2 # -> "10"
"%b" % -2 # -> "..10"

B - , 0B .
d ( i u) - .
"%d" % 0x01 # -> "1"

o - . 2 ..
.
"%o" % 2 # -> "2"
"%o" % -2 # -> "..76"

x - . 2
.. .

C.

257

"%x" % 2 # -> "2"


"%x" % -2 # -> "..fe"

X - , 0X, .
:
e - .
"%e" % 1.2 # -> "1.200000e+00"

E - , E.
f - .
"%.3f" % 1.2 # -> "1.200"

g - ,
-4 .
.
"%.1g" % 1.2 # -> "1"
"%g" % 123.4 # -> "1e+02"

G - , E.
a - : ,
0x, p, .
"%.3a" % 1.2 # -> "0x1.333p+0"

A - , 0X
P.
:
c - .
"%" % ?h # -> "h"

p - object.inspect .
"%p" % ?h # -> "\"h\""

s - . .
"%.3s" % "Ruby" # -> "Rub"

:
- - , .
4b" % 2 # -> "10

"

0 ( ) - .
"%04b" % 2 # -> "0010"

C.

258

+ ( ) -
. oxXbB .
"%+b" % -2 # -> "-10"

# ( bBoxXaAeEfgG) - .
o
, .
"%#o" % 2 # -> "02"

xXbB .
"%#X" % 2 # -> "0X2"

aAeEfgG .
"%#.0E" % 2 # -> "2.E+00"

gG .
"%#G" % 1.2 # -> "1.20000"

* - . .
"%*d" % [ -2, 1 ] # -> "1 "

, ,
.
$ ( 1).
.
"%3$d, %1$d, %1$d" % [ 1, 2, 3 ] # -> "3, 1, 1"

<>
.
"%<two>d, %<one>d" % { one: 1, two: 2, three: 3 } # -> "2, 1"

:

. .
x = ?R # -> "R"

,
object.to_ary,
. .
x, y

[ 1, 2 ] # -> [ 1, 2 ]

x # -> 1
y # -> 2

, . .
x

?Y, ?N # -> [ "Y", "N" ]

x # -> "Y"

. .
x, y

?Y, ?N # -> [ "Y", "N" ];

x # -> "Y"
y# -> "N"
x, y

y, x # -> [ "N", "Y" ]

x # -> "N"
y # -> "Y"

, ,
.
, .
x,

?Y, ?N # -> [ "Y", "N" ]

x# -> "Y"

, ,
. , . .

D.

x, y, z

?Y, ?N

260

# -> [ "Y", "N" ]

x # -> "Y"
y # -> "N"
z # -> nil

, ,
, .
.
x, y

?Y, ?N, ?Q # -> [ "Y", "N", "Q" ]

x # -> "Y"
y # -> "N"

(*),
.
( object.to_splat). .
. .
x, y

*(1..3) # -> [ 1, 2, 3 ]

x # -> 1
y # -> 2

(*),
. .
*x, y

?Y, ?N # -> [ "Y", "N" ]

x # -> [ "Y" ]
y # -> "N"
*x, y

?Y, ?N, ?Q # -> [ "Y", "N", "Q" ]

x # -> [ "Y", "N" ]


y # ->"Q"
x, *y, z

?Y, ?N, ?Q, ?R # -> [ "Y", "N", "Q", "R" ]

x # ->"Y"
y # ->[ "N", "Q" ]
z # ->"R"

,
:
1. ;
2. .

D.

.
x, (y, z) = ?Y, ?N
x = ?Y
(y, z) = ?N
y, z = ?N
y = ?N
z = nil

# -> [ "Y", "N" ]

261

:
replace: , . uFFFD Unicode ? ;
:invalid => :replace - ;
:undef => :replace - ;
:fallback => encoding - ;
:xml => :text - XML CharData.
HTML 4.0:
& &amp;
< &lt;
> &gt;
&x ( x - ).
:xml => :attr - XML AttrValue.
HTML 4.0:
& &amp;
< &lt;
> &gt;

"

&quot;

&x ( x - ).
cr_newline: true - LF (\n) CR (\r);
crlf_newline: true - LF (\n) CRLF (\r\n);
universal_newline: true - CR (\r) CRLF (\r\n) LF (\n).


.
() ( ).
:
;
,
;
(*) ;
sSiIlL , ;
> < (l_> L!<).

:
C - 8- (unsigned integer unsigned char);
c - 8- (signed integer signed char);
S - 16- (uint_16t);
s - 16- (int_16t);
L - 32- (uint_32t);
l - 32- (int_32t);
Q - 64- (uint_64t);
S_ (S!) - (unsigned
short);
s_ (s!) - (signed short);
I (I_ I!) - (unsigned integer);
i (i_ i!) - (signed integer);
L_ (L!) - (unsigned
long);
l_ (l!) - (signed long);
N - 32- ( );

F.

264

n - 16- ( );
V - 32- (VAX);
v - 16- (VAX);
U - UTF-8 ;
w - BER- .

:
D, d - ;
F, f - ;
E - , ;
e - ;
G - , ;
g - .

:
A - ASCII
;
a - ;
Z - ;
B - (MSB );
b - (LSB );
H - (hight nibble );
h - (low nibble );
u - UU- ;
M - MIME- (RFC2045);
m - base64- (RFC2045, 0, RFC4648);
P - ( );
p - , .

:
@ - ;
X - ;
x - .


:
%[][][].
, .
. ,
, .

:
_
0
^
#

- ;
- ;
- ( );
- ;
- .

:
%Y - ;
Time.local( 1990, 3, 31 ).strftime ": %Y" # -> ": 1990"
Time.local( 1990, 3, 31 ).strftime ": %7Y" # -> ": 0001990"
Time.local( 1990, 3, 31 ).strftime ": %-7Y" # -> ": 1990"
Time.local( 1990, 3, 31 ).strftime ": %_7Y" # -> ":

1990"

Time.local( 1990, 3, 31 ).strftime ": %07Y" # -> ": 0001990"

%G - , ;
Time.local( 1990, 3, 31 ).strftime ": %G" # -> ": 1990"

%y - 100 ( 00 99);
Time.local( 1990, 3, 31 ).strftime ": %y" # -> ": 90"

%g - 100 ( 00 99),
;
Time.local( 1990, 3, 31 ).strftime ": %g" # -> ": 90"

%C - , 100 (20 2011);


Time.local( 1990, 3, 31 ).strftime ": %C" # -> ": 19"

266

G.

:
%b (%h) - ( );
Time.local( 1990, 3, 31 ).strftime ": %b" -> ": Mar"

%B - ;
Time.local(1990, 3, 31).strftime ": %B" # -> ": March"
Time.local(1990, 3, 31).strftime ": %^B" # -> ": MARCH"
Time.local(1990, 3, 31).strftime ": %#B" # -> ": MARCH"

%m - ( 01 12);
Time.local( 1990, 3, 31 ).strftime ": %m" -> ": 03"

:
%U - ( 00 53), ;
Time.local( 1990, 3, 31 ).strftime ": %U" -> ": 12"

%W - ( 00 53), ;
Time.local( 1990, 3, 31 ).strftime ": %W" -> ": 13"

%V - ( ISO 8601 - 01 53);


Time.local( 1990, 3, 31 ).strftime ": %V" -> ": 13"

:
%j - ( 001 366);
Time.local( 1990, 3, 31 ).strftime ": %j" # -> ": 090"

%d - ;
Time.local( 1990, 3, 3 ).strftime ": %d" # -> ": 03"

%e - ;
Time.local( 1990, 3, 3 ).strftime ": %e" # -> ":

3"

%a - ( );
Time.local( 1990, 3, 31 ).strftime ": %a" # -> ": Sat"

%A - ;
Time.local( 1990, 3, 31 ).strftime ": %A" # -> ": Saturday"

%u - ( 1 7, - 1);
Time.local( 1990, 3, 31 ).strftime ": %u" # -> ": 6"

%w - ( 0 6, - 0);
Time.local( 1990, 3, 31 ).strftime ": %w" # -> ": 6"

267

G.

:
%H - 24 ( 00 23);
Time.local( 1990, 3, 31 ).strftime ": %H" # -> ": 00"

%k - 24 ( 0 23);
Time.local( 1990, 3, 31 ).strftime ": %k" # -> ":

0"

%I - 12 ( 01 12);
Time.local( 1990, 3, 31 ).strftime ": %I" # -> ": 12"

%l - 12 , - ( 0 12);
Time.local( 1990, 3, 31 ).strftime ": %l" # -> ": 12"

%p - (AM PM);
Time.local( 1990, 3, 31 ).strftime "%I %p" # -> "12 AM"

%P - (am pm);
Time.local( 1990, 3, 31 ).strftime "%I %P" # -> "12 am"

:
%M - ( 00 59);
Time.local( 1990, 3, 31 ).strftime ": %M" # -> ": 00"

%S - ( 00 60);
Time.local( 1990, 3, 31 ).strftime ": %S" # -> ": 00"

%N - .
%3N - ;
%6N - ;
%9N - ( );
%12N - .
%L - ( 000 999);
Time.local( 1990, 3, 31 ).strftime ": %L" # -> ": 000"

%s - , 1970-01-01 00:00:00 UTC;


Time.local( 1990, 3, 31 ).strftime "%s" # -> "638827200"

:
%D - "%m/%d/%y";
Time.local( 1990, 3, 31 ).strftime ": %D"
# -> ": 03/31/90"

%F - "%Y-%m-%d" ( ISO 8601);

G.

Time.local( 1990, 3, 31 ).strftime ": %F"


# -> ": 1990-03-31"

%v - "%e-%b-%Y" ( VMS);
Time.local( 1990, 3, 31 ).strftime ": %v"
# -> ": 31-MAR-1990"

%c - ;
Time.local( 1990, 3, 31 ).strftime ": %c"
# -> ": Sat Mar 31 00:00:00 1990"

%r - "%I:%M:%S

%p";

Time.local( 1990, 3, 31 ).strftime "%r" # -> "12:00:00 AM"

%R - "%H:%M";
Time.local( 1990, 3, 31 ).strftime "%R" # -> "00:00"

%T - "%H:%M:%S";
Time.local( 1990, 3, 31 ).strftime "%T" # -> "00:00:00"

:
%n - ;
Time.local( 1990, 3, 31 ).strftime "%D %n %F %n %c"
# -> "03/31/90 \n 1990-03-31 \n Sat Mar 31 00:00:00 1990"

%t - ;
Time.local( 1990, 3, 31 ).strftime "%D %t %F %t %c"
# -> "03/31/90 \t 1990-03-31 \t Sat Mar 31 00:00:00 1990"

:
%x - ;
Time.local( 1990, 3, 31 ).strftime "%x" # -> "03/31/90"

%X - ;
Time.local( 1990, 3, 31 ).strftime "%X" # -> "00:00:00"

%z - UTC;
Time.local( 1990, 3, 31 ).strftime "%z" # -> "+0400"

%:z - ;
Time.local( 1990, 3, 31 ).strftime "%:z" # -> "+04:00"

268

G.

%::z - , ;
Time.local( 1990, 3, 31 ).strftime "%::z" # -> "+04:00:00"

%Z - ;
Time.local( 1990, 3, 31 ).strftime "%Z" # -> "MSD"

%% - .

269


(mode) .

:
r - ;
r+ - , ( );
w - ( ).
;
w+ - , ( ).
;
a - ( ). ;
a+ - , ( ).
;
b - ( ). ASCII .
Windows;
t - ( ).
:
.
- .
.
-
. .
,
, - .
,
: "w+:ascii:utf-8". , .
- File::Constants.

H.

271

:
mode: ;
textmode: true, ;
binmode: true, ;
autoclose: true, , ;
external_encoding: ;
internal_encoding: . , ;
encoding: external:internal.
, .

Linux
- Linux ( ). ( ).

I.1.
- , , (
);
- , .
, . -
, .
.

( , ..);
() - , .
, . -
, .
1. .
2. ;
- , .
, . .
- ;
- ,
- .
.

I.2.

273

.
- .
- , , .

I.2.
.
Ruby - ,
object.to_path.
- , ( ), .
:
- ,
;
- , .

:
, ..;
.;
~;
Windows
(\), Linux - (/);
.
* - ;
** - ( );
? - ;
[...] -
;
[^...] - , ;
{ } - , (Ruby 2.0).
, .

I.3.

274

:
File::FNM_SYSCASE - ( );
File::FNM_CASEFOLD - ;
File::FNM_PATHNAME - ?,
( );
File::FNM_NOESCAPE -
, ;
File::FNM_DOTMATCH -
, (
Linux);
File::FNM_EXTGLOB - (Ruby 2.0).
. , ,
.

I.3.

.
: , .
.
, .
,
(
).
, ;
,
.
Windows. .

I.3.

275

(permission):
700 - , ;
400 - ;
200 - ;
100 - ( );
70 - , ;
40 - ;
20 - ;
10 - ( );
7 - , ;
4 - ;
2 - ;
1 - (
).
,
.

:
4000 - ;
2000 - ;
1000 - , .
,
.
0444 - .
. ;
UID - , ;
EUID - , ;
GUID - , , ;
EGUID - ,
;

.
,
.

I.4.

276

I.4.
:
File::RDONLY - ;
File::WRONLY - ;
File::RDWR - , ;
File::APPEND - ( );
File::CREAT - .
. ;
File::DIRECT - ;
File::EXCL - ;
File::NONBLOCK - , , ;
File::TRUNC - ( );
File::NOCTTY - , ;
File::BINARY - ;
File::SYNC, File::DSYNC, File::RSYNC - c .
, , ;
File::NOFOLLOW - , ;
File::NOATIME - .


- - .

, . , - . ,
. , , ( ..)
. , Ruby
.
.
. Ruby. -
, .
,
.
Ruby, :
http://www.google.com - ;
http://www.rubygems.org - ( Ruby RubyGems);
http://www.ruby-toolbox.com - , gem- ();
http://github.com - .
Ruby-.