Ruby Class基础1
Ruby记录
其实用了Ruby时间不短了,但是很多知识点由于时间的原因老是断断续续,导致又要花时间去重新了解。有了自己的blog
,可以永久记录下来和更新了,作为自己的一个阶段性工作,内容包括基础性的以及深入性的。
Ruby中的Class
1
2
3
4
5
6
7
8
class Book
@@Book_num=0
def initialize(id, name, author)
@id = id
@name = name
@author = author
end
end
class命名必须是Camel规则,其中initialize是特殊方法,用于new
方法新建对象时的调取方法, @
变量是实例变量,@@
变量是类变量
1
2
3
4
5
6
book1 = Book.new
puts book1
:3:in `initialize': wrong number of arguments (given 0, expected 3) (ArgumentError)
from 1.rb:10:in `new'
from 1.rb:10:in `<main>'
如果不带参数的话会提示报错
1
2
3
4
book1 = Book.new(1, 'book_name1', 'author_1')
puts book1
#<Book:0x00007f17c7aa35d0>
携带正确参数后,new后就生成了对象
1
2
3
4
5
6
book1 = Book.new(1, 'book_name1', 'author_1')
puts book1.id, book1.name, book1.author
rb:12:in `<main>': undefined method `id' for an instance of Book (NoMethodError)
puts book1.id, book1.name, book1.author
^^^
当想看实例的属性时会提示报错,因为这时候除了构造方法initialize是没有定义其他方法的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Book
@@Book_num=0
def initialize(id, name, author)
@id = id
@name = name
@author = author
end
def show
puts @id, @name, @author
end
end
book1 = Book.new(1, 'book_name_1', 'author_1')
book1.show
1
book_name_1
author_1
定义一个show方法,就可以查看实例的属性了
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
class Book
@@book_num = 0
def initialize(id, name, author)
@id = id
@name = name
@author = author
@@book_num += 1
end
def show
puts @id, @name, @author
end
def show_count
puts @@book_num
end
def self.book_num
@@book_num
end
end
book1 = Book.new(1, 'book_name_1', 'author_1')
book2 = Book.new(2, 'book_name_2', 'author_2')
puts Book.book_num
2
在initialize方法构造得时候让类变量@@book_num
自增,这样就可以统计生成了多少Book实例,注意其中def self.book_num
构建得是一个类方法book_num
,类方法可以不用新建实例去访问,可以直接用Book.book_num
访问,这里生成了2个book, 所以类变量@@book_num
就是2
Ruby相关文章
This post is licensed under
CC BY 4.0
by the author.