当前位置: 首页 > 图文教程 > 脚本技术 > Ruby > Ruby self在不同环境的含义

Ruby
print不自动换行,puts会自动换行
windows和linux下Ruby的下载与安装
Ruby入门点滴-Ruby的安装
Ruby入门介绍
什么是ruby和Ruby概述
RUBY文档中心-学习开始
ruby 简单例子
Ruby 字符串处理
ruby 正则表达式 教程
ruby 数组使用教程
ruby 一些简单的例子
ruby 流程控制 方法
ruby 迭代器使用方法
ruby 面向对象思维 概念
rudy 方法 分析
分析 rudy 类
rudy 继承 概念
rudy 重载方法 详解
剖析 rudy 访问控制
ruby 单态方法 分析

Ruby self在不同环境的含义


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-11   浏览: 174 ::
收藏到网摘: n/a

Ruby的self在不同的环境中有不同的含义,这点和java的this不同,原因是java实际上只有一种环境--在class的实例方法定义中使用,代表访问这个方法参数自动传进的那个对象。 而由于ruby作为一个完全纯净的面向对象语言,任何东东都是对象,方法是对象,类也是对象...,所以self就会有很多环境,区分不同环境的self含义才能更好的理解程序的含义
一、Top Level Context
Ruby代码
puts self
打印出main,这个代表Object的默认对象main.
二、在class或module的定义中:
在class和module的定义中,self代表这个class或这module对象:
Ruby代码
class S
puts 'Just started class S'
puts self
module M
puts 'Nested module S::M'
puts self
end
puts 'Back in the outer level of S'
puts self
end
输出结果:
写道
>ruby self1.rb
Just started class S
Nested module S::M
S::M
Back in the outer level of S
>Exit code: 0
三、在实例的方法定义中:
这点和java的this代表的东东一样:程序自动传递的调用这个方法的对象
Java代码
class S
def m
puts 'Class S method m:'
puts self
end
end
s = S.new
s.m
运行结果:
写道
>ruby self2.rb
Class S method m:
#<S:0x2835908>
>Exit code: 0
四、在单例方法或者类方法中:
单例方法是针对一个对象添加的方法,只有这个对象拥有和访问这个方法,这时候self是拥有这个方法的对象:
Ruby代码
# self3.rb
obj = Object.new
def obj.show
print 'I am an object: '
puts "here's self inside a singleton method of mine:"
puts self
end
obj.show
print 'And inspecting obj from outside, '
puts "to be sure it's the same object:"
puts obj
运行结果:
写道
ruby self3.rb
I am an object: here's self inside a singleton method of mine:
#<Object:0x2835688>
And inspecting obj from outside, to be sure it's the same object:
#<Object:0x2835688>
>Exit code: 0
在类方法中self代表这个类对象:
Ruby代码
# self4.rb
class S
def S.x
puts "Class method of class S"
puts self
end
end
S.x
运行结果:
写道
>ruby self4.rb
Class method of class S
>Exit code: 0
从上面的例子我们可以看出不管是ruby的self还是java的this都表示在当前的环境下你可以访问的当前的或者默认的对象。