-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeffrent_context.rb
More file actions
88 lines (71 loc) · 2.47 KB
/
deffrent_context.rb
File metadata and controls
88 lines (71 loc) · 2.47 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
class Planet
@order = 'class instance variable'
def initialize num
@order = num
end
def test_class_eval_for_class
self.class.class_eval{ @order }
end
def test_instance_eval_for_class
self.class.instance_eval{ @order }
end
def test_method_def_class_eval
# метод определяется в контексте класса Planet
self.class.class_eval{ def has_live?; false; end }
end
def test_method_def_instance_eval_for_instance
# метод определяется в контексте синглтон класса объекта self
instance_eval{ def has_live?; 'Yes'; end }
end
def test_method_def_inline_for_instance
# метод определяется в контексте класса Planet
def has_live?; '+'; end
end
def test_method_def_instance_eval_for_class
# метод определяется в контексте синглтон класса объекта Planet
self.class.instance_eval{ def has_live?; 'It depends'; end }
end
instance_eval do
# определяем метод в контексте синглтон класса объекта self. Здесь self - Planet
def with_satellite;
'Earth'
end
end
class_eval do
# определяем метод в контексте класса Planet
def with_satellite;
'Mars'
end
end
end
earth = Planet.new 3
mars = Planet.new 4
p mars.instance_eval{ @order } # 4
p mars.class_eval{ @order } # no method
p mars.module_eval{ @order } # no method
p earth.test_class_eval_for_class # class instance variable
p earth.test_instance_eval_for_class # class instance variable
mars.test_method_def_class_eval
p mars.has_live? # false
p earth.has_live? # false
p earth.class.has_live? # no method
p earth.singleton_class.has_live? # no method
earth.test_method_def_instance_eval_for_instance
p mars.has_live? # false
p earth.has_live? # 'Yes'
p earth.class.has_live? # no method
p earth.singleton_class.has_live? # no method
earth.test_method_def_inline_for_instance
p mars.has_live? # '+'
p earth.has_live? # 'Yes'
p earth.class.has_live? # no method
p earth.singleton_class.has_live? # no method
earth.test_method_def_instance_eval_for_class
p mars.has_live? # '+'
p earth.has_live? # 'Yes'
p earth.class.has_live? # 'It depends'
p earth.singleton_class.has_live? # 'It depends'
p Planet.singleton_methods.include? :has_live? # true
p mars.with_satellite # Mars
p Planet.with_satellite # Earth
#test_class_eval