• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >ruby > Ruby self在不同环境的含义

Ruby self在不同环境的含义

作者: 字体:[增加 减小] 来源:互联网

通过本文主要向大家介绍了ruby self,ruby的含义,ruby名字的含义,ruby环境搭建,ruby环境等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
而由于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都表示在当前的环境下你可以访问的当前的或者默认的对象。 </div>

您可能想查找下面的文章:

  • Ruby self在不同环境的含义

相关文章

  • Linux下Redis数据库的安装方法与自动启动脚本分享
  • ruby 实变量
  • ruby 单态方法 分析
  • Ruby中的block、proc、lambda区别总结
  • Ruby 中一些百分号(%)的用法小结
  • Ubuntu系统安装Ruby语言的三种方法
  • Ubuntu上配置Ruby on Rails框架及RubyMine IDE开发环境
  • rails创建应用程序实例
  • 初步讲解Ruby编程中的多线程
  • 详解Ruby中范围的概念

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • 在Ruby on Rails中使用AJAX的教程
    • Ruby实现网页图片抓取
    • Rails中遇到错误跳转到统一提示错误页的方法
    • Ruby中任务构建工具rake的入门学习教程
    • Ruby中使用Nokogiri包来操作XML格式数据的教程
    • Ubuntu上配置Ruby on Rails框架及RubyMine IDE开发环境
    • Monkey Patch猴子补丁编程方式及其在Ruby中的运用
    • 设计模式中的模板方法模式在Ruby中的应用实例两则
    • 使用Ruby程序实现web信息抓取的教程
    • Ruby的25个编程细节(技巧、实用代码段)

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有