几种Ruby self应用方法介绍

开发 开发工具
Ruby self对于一个Ruby语言初学者来说还是比较生疏的。我们希望大家可以通过这篇文章帮助大家提高对Ruby语言的了解程度。

Ruby语言通常被人们理解为是一种解释型脚本语言。在对Ruby语言的学习中,我们需要不断的从编码实践中去总结经验,帮助我们提高编程能力。#t#

Ruby self在不同的环境中有不同的含义,这点和java的this不同,原因是java实际上只有一种环境--在class的实例方法定义中使用,代表访问这个方法参数自动传进的那个对象。

而由于ruby作为一个完全纯净的面向对象语言,任何东东都是对象,方法是对象,类也是对象...,所以Ruby self就会有很多环境,区分不同环境的self含义才能更好的理解程序的含义。

一、Top Level Context

puts self

打印出main,这个代表Object的默认对象main.

二、在class或module的定义中:

在class和module的定义中,self代表这个class或这module对象: 

  1. class S   
  2. puts 'Just started class S'   
  3. puts self   
  4. module M   
  5. puts 'Nested module S::M'   
  6. puts self   
  7. end   
  8. puts 'Back in the 
    outer level of S'   
  9. puts self   
  10. end  

输出结果: 

  1. >ruby self1.rb   
  2. Just started class S   
  3. Nested module S::M   
  4. S::M   
  5. Back in the outer level of S   
  6. >Exit code: 0  

三、在实例的方法定义中:

这点和java的this代表的东东一样:程序自动传递的调用这个方法的对象

 

  1. class S   
  2. def m   
  3. puts 'Class S method m:'   
  4. puts self   
  5. end   
  6. end   
  7. s = S.new   
  8. s.m  

运行结果:

  1. >ruby self2.rb   
  2. Class S method m:   
  3. #<S:0x2835908>   
  4. >Exit code: 0  

四、在单例方法或者类方法中:

单例Ruby self方法是针对一个对象添加的方法,只有这个对象拥有和访问这个方法,这时候self是拥有这个方法的对象:

  1. # self3.rb   
  2. obj = Object.new   
  3. def obj.show   
  4. print 'I am an object: '   
  5. puts "here's self inside a 
    singleton method of mine:"   
  6. puts self   
  7. end   
  8. obj.show   
  9. print 'And inspecting obj 
    from outside, '   
  10. puts "to be sure it's the
     same object:"   
  11. puts obj  

运行结果: 

 

  1. ruby self3.rb   
  2. I am an object: here's self 
    inside a singleton method of mine:   
  3. #<Object:0x2835688>   
  4. And inspecting obj from outside,
     to be sure it's the same object:   
  5. #<Object:0x2835688>   
  6. >Exit code: 0  

在类方法中Ruby self代表这个类对象: 

  1. # self4.rb   
  2. class S   
  3. def S.x   
  4. puts "Class method 
    of class S"   
  5. puts self   
  6. end   
  7. end   
  8. S.x  

运行结果:

  1. >ruby self4.rb   
  2. Class method of class S   
  3. >Exit code: 0  

从上面的例子我们可以看出不管是Ruby self还是java的this都表示在当前的环境下你可以访问的当前的或者默认的对象。

责任编辑:曹凯 来源: jb51.net
相关推荐

2009-12-17 11:14:50

Ruby on Rai

2009-12-16 15:14:43

Ruby on Rai

2009-12-14 16:26:40

Ruby复制文件

2009-12-17 17:13:23

Ruby for Ec

2009-12-15 15:19:30

Ruby访问控制

2009-12-16 13:48:06

Ruby Web开发框

2009-12-15 17:04:56

Ruby使用HTTP协

2009-12-16 15:04:26

Ruby实现strea

2009-12-16 14:04:04

Ruby对象初始化

2009-12-15 14:46:04

Ruby类常量

2009-12-24 16:11:07

WPF图像处理

2009-12-14 13:56:12

Ruby特点

2009-12-17 17:46:26

Ruby编写问题

2009-12-10 17:02:50

PHP站点性能

2021-07-07 05:53:23

PythonPython 语法加密源代码

2011-06-16 10:48:33

session

2009-12-22 17:30:47

WCF Address

2009-12-17 15:02:32

Ruby on Rai

2009-12-23 18:06:25

WPF模板

2009-12-14 13:06:08

Ruby数字类型
点赞
收藏

51CTO技术栈公众号