【Ruby】new & initialize

Class

define a class

1
2
3
4
class Klass
def initialize()
end
end

create instance by new

1
2
3
4
5
6
7
8
9
10
11
12
class Hello
def initialize
end

def talk
puts "Hello world"
end
end

hello = Hello.new
hello.talk
# => Hello world

new & initialize

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Hello
@@name = nil

def initialize(name)
@@name = name
end

def talk
puts "Hello #{@@name}"
end
end

hello = Hello.new("jobs")
hello.talk

# => Hello job

Basic Usage of initialize

Do not override the initialize or return in initialize

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Hello
def initialize(he)
@he = he
end

def initialize(he,her)
@he = he
@her = her
end

def hello
puts "hello, Mt." + @he.to_s + " and Ms." + @her.to_s
end

end

hello = Hello.new("Kevin", "Jane")
hello.hello
#=>hello, Mt.Kevin and Ms.Jane

How tocallinitialize` method of parent class

Child class may use the super method to class the initialize method of parent class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Human
def initialize(name)
@name = name
end
end

class Woman < Human
def initialize(name, bag)
super name
@bag = bag
end
def who?
puts "She name is " + @name + " having bag of " + @bag
end
end

w = Woman.new('Kity','Coach')

w.who?
#=> She name is Kity having bag of Coach