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
|
# class
class User
def initialize name, age
@name = name
@age = age
end
# getter
def name
@name
end
def age
@age
end
end
user = User.new("Hello", 18)
puts user.name
puts user.age
# class
class User
def initialize name, age
@name = name
@age = age
end
# getter
def name
@name
end
def age
@age
end
# setter
def name= name
@name = name
end
def age= age
@age = age
end
end
user = User.new("Hello", 18)
puts user.name
puts user.age
puts "-" * 30
user.name = "hello 2"
user.age = 20
puts user.name
puts user.age
# class, attr_reader, attr_writer
class User
attr_reader :name
attr_reader :age
attr_writer :name
attr_writer :age
def initialize name, age
@name = name
@age = age
end
end
user = User.new("Hello", 18)
puts user.name
puts user.age
puts "-" * 30
user.name = "hello 2"
user.age = 20
puts user.name
puts user.age
# class, method
class User
attr_accessor :name
attr_accessor :age
def initialize name, age
@name = name
@age = age
end
def say_hi
puts "hello #{@name}, i am #{@age}"
end
end
user = User.new("Hello", 18)
user.say_hi
|