发布于 2016-01-26 21:43:59 | 68 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Ruby教程,程序狗速度看过来!

Ruby编程语言

Ruby,一种为简单快捷的面向对象编程(面向对象程序设计)而创的脚本语言,在20世纪90年代由日本人松本行弘开发,遵守GPL协议和Ruby License。它的灵感与特性来自于 Perl、Smalltalk、Eiffel、Ada以及 Lisp 语言。


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都表示在当前的环境下你可以访问的当前的或者默认的对象。

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务