Ruby on Rails 入门之:(10) Ruby中的对象

1. 类的定义与使用

1.1 类的定义


    Ruby是一个完全的面向对象的语言,在Ruby中所有的一切的数据类型都是对象,然而Ruby是一种弱类型的语言,也就是说变量在使用之前不许要定义,而且不用分别变量的类型。

    Ruby中类的定义如代码所示:

#encoding:gbk
puts "test of class in Ruby!";

class Animal
	puts "i amm an animal!"

end

在类中的puts语句会直接输出,不像C#中的类没有作用,这里的类在运行的时候puts语句会运行。

在Ruby中要求类的第一个字符必须是大写字符,如果第一个字符不是大写字符,那么程序在运行的时候会出现错误。

如果一个类中有多个输出语句,将会按照顺序进行输出。

#encoding:gbk
puts "test of class in Ruby!";

class Animal
	puts "i amm an animal!"

	def cal
		puts "calculate...";
	end

	puts "the second puts";
end

1.2 self关键字


c++中使用this关键字来表示当前对象,在Ruby中使用self表示当前对象。

#encoding:gbk
puts "test of class in Ruby!";

class Animal
	puts "i amm an animal!"

	def cal
		puts "calculate...";
	end

	#puts "the second puts";

	puts self;
	puts self.class;
end

输出结果为:

watkins@watkins:~/temp/workspace/ruby$ ruby class.rb 
test of class in Ruby!
i amm an animal!
Animal
Class
watkins@watkins:~/temp/workspace/ruby$ 

我们再看看在一个具体的对象里输出的self是什么,代码如下:

#encoding:gbk
puts "test of class in Ruby!";

class Animal
	puts "i amm an animal!"

	def cal
		puts "calculate...";
	end

	#puts "the second puts";

	puts self;
	puts self.class;

	def put
		puts self;
		puts self.class;
	end
end

a = Animal.new;
a.put;

输出结果为:

watkins@watkins:~/temp/workspace/ruby$ ruby class.rb 
test of class in Ruby!
i amm an animal!
Animal
Class
#<Animal:0xb77c272c>
Animal
watkins@watkins:~/temp/workspace/ruby$ 

之所以会出现这样的情况,是因为我们在类中直接使用puts语句输出self的时候,我们作用的对象是一个类,不是一个具体的对象,当我们作用于a.put的时候,我们的具体的操作的是一个具体的对象,所以会输出这个对象的地址。那么这个对象的类型也是Animal类型。这里需要特别注意。

1.3 追加类


在使用类的时候,如果有两个或多个同名的类,系统会自动的合并这几个类。

#encoding:gbk
puts "test of class in Ruby!";

class Animal
	puts "i amm an animal!"

	def cal
		puts "calculate...";
	end

	#puts "the second puts";

	puts self;
	puts self.class;

	def put
		puts self;
		puts self.class;
	end
end

class Animal
	def sayHello
		puts "hello";
	end
end

a = Animal.new;
a.put;
a.sayHello;


1.4 嵌套类


嵌套类的使用要使用::双冒号来引用里面的嵌套类。

#encoding:gbk

class Animal
	class Head
		def put
			puts "this is class Head's method put";
		end
	end
end

h = Animal::Head.new
h.put;

还可以在类的外部直接定义嵌套类:

#encoding:gbk

class Animal
	class Head
		def put
			puts "this is class Head's method put";
		end
	end
end

class Animal::Body
	def put
		puts "this is class Body's method put";
	end
end

h = Animal::Head.new
h.put;

b = Animal::Body.new
b.put;


1.5 特殊类


在Ruby中还可一位某个特定的对象追加一些方法和属性,这些方法和属性封装到一个类中直接追加到对象中。这个类没有特定的类名,所以不能作为普通类使用,只能当作特殊类使用。

#encoding:gbk

class Animal
	#empty
end

a = Animal.new;

class << a
	def put
		puts "added method";
	end
end

a.put;

这里我们定义了一个空的类Animal, 然后为对象a添加了一个方法。特殊类追加方法和属性只能给具体的对象追加,不能给类追加。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值