attr_module2.rb

Сергей Е, 04/28/2012 01:53 PM

Download (998 Bytes)

 
1
module Variables
2

    
3
        def print_var
4
                print "In module #{self.class.name}: #{@variable}\n"
5
        end
6

    
7
        def print_class_var
8
                print "In module class-variable #{self.class.name}: #{@@class_variable}\n"
9
        end
10

    
11
        def set_variables(var, cvar)
12
                @variable = var
13
                @@class_variable = cvar
14
        end
15

    
16
end
17

    
18

    
19
class A
20

    
21
        include Variables
22

    
23
        def initialize(var, cvar)
24
                @variable = var
25
                @@class_variable = cvar
26
        end
27

    
28
        def print_variables
29
                print "variables: #{@variable}, #{@@class_variable}\n"
30
        end
31

    
32
        def self.print_class_a_variables
33
                print "Class '#{self.class.name}' variable: #{@@class_variable}\n"
34
        end
35

    
36
end
37

    
38
class B < A
39
end
40

    
41
a = A.new(123, 456)
42

    
43
A.print_class_a_variables
44
B.print_class_a_variables
45

    
46
a.print_variables
47

    
48
a.print_var
49

    
50
a.print_class_var # fail: :8:in `print_class_var': uninitialized class variable @@class_variable in Variables (NameError)
51
                                                                        # Why? I set '@@class_variable` in 'initialize'
52

    
53
a.set_variables(12, 33) # Once again set '@@class_variavle'
54

    
55
a.print_class_var # But this method is tested