-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdo_ruby_2.rb
More file actions
173 lines (140 loc) · 2.89 KB
/
do_ruby_2.rb
File metadata and controls
173 lines (140 loc) · 2.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
class Foo
def foo(arg=nil)
p arg
end
end
class Bar < Foo
def foo(arg)
# 5を引数にして呼び出す
super(5) # => 5
# 5を引数にして呼び出す
super(arg) # => 5
# 5を引数にして呼び出す super(arg)の略記法
super # => 5
arg = 1
# 1を引数にして呼び出す super(arg)の略記法
super # => 1
# 引数なしで呼び出す
super() # => nil
end
end
Bar.new.foo 5 # => nil
class Sample
@value = 'hello'
def value
@value # !> instance variable @value not initialized
end
end
Sample.new.value # => nil
Sample.class_eval { @value } # => "hello"
#
class Foo
@v1 = 1
def self.read
@v1
end
def write
@v1 = 2
end
def read
@v1
end
end
obj = Foo.new
obj.write # => 2
obj.read # => 2
Foo.read # => 1
#
foo = Foo.new
foo.class # => Foo
# foo.superclass # =>
@@v1 = 1 # !> class variable access from toplevel
class Foo
@@v1 = 2
end
p @@v1 # 2 # !> class variable access from toplevel
# クラス変数は親と子、共有で使う
# http://ref.xaio.jp/ruby/classes/object/extend
module M
def m
'aa'
end
end
obj = Object.new
obj.extend M
obj.m # => "aa"
class C
extend M
end
C.m # => "aa"
#c.new.m # =>
# includeの位置を変えると表示される結果が異なる
module M
@@x = 100
end
class A
@@x = 500
include M
end
module M
p @@x # => 100
end
class A
p @@x # => 100 # !> class variable @@x of A is overtaken by M
end
module M2
@@x = 100 # => 100
end
class A
include M
@@x = 500
end
module M
p @@x # => 500
end
class A
p @@x # => 500
end
# moduleで定義されたクラス変数(モジュール変数)は、そのmoduleをincludeしたclass間でも共有される
#
module FooModule
@@foo = 1
end
class Bar
include FooModule
@@foo += 1 # => 2
end
class Baz
include FooModule
@@foo += 1 # => 3
end
# 親クラスに、子クラスで既に定義されている同名のクラス変数を追加した場合は、
# 子クラスのクラス変数は子クラスで保存される
#
class FooBar
end
class BarFooBar < FooBar
@@v = :bar
end
class FooBar
@@v = :foobar
end
class BarFooBar
@@v # => :foobar # !> class variable @@v of BarFooBar is overtaken by FooBar
end
class FooBar
@@v # => :foobar
end
# module AB
# p @@x # =>
# end
# >> 5
# >> 5
# >> 5
# >> 1
# >> nil
# >> 2
# >> 100
# >> 100
# >> 500
# >> 500