博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HeadFIrst Ruby 第二章总结 methods and classes
阅读量:4564 次
发布时间:2019-06-08

本文共 1086 字,大约阅读时间需要 3 分钟。

HeadFIrst Ruby 第二章总结 methods and classes

前言

这一章讲了如何创建自己的 class,并且讲了在用 class 创建 object 的两个要素: instance variables 和 instance methods.和它们需要注意的一些问题.

创建 method 相关

问题1:括号 be or not be?

在 Ruby 中,如果需要创建的 method 包含参数,那么后面应该有“()” ;

如果不需要任何参数,则不需要加“()”,在调用函数的时候也不需要加.

问题2: local variable 和 instance variable 的区别

local variable:在定义的 method 范围之后,就 don't exisit 了

instance variable: 在定义的 class 的范围内都 exisit.

新知1:在 Terminal 中运行程序的另一种方法

特点:可以 load 这个 file 之后,然后进行交互的编程.

步骤:

  1. 在 Terminal 中输入 “irb -I ."
  2. 接着在提示下输入 "require xxx.rb"

新知2: atttribute accessor methods

定义:为了实现 encapsulation,如果想要给创建的 instance 传递参数的话,就需要通过 accessor methods 进行传递,它分为两类: attribute writer 和 attribute reader

attribute writer

定义:用于set an instance variable

惯例: attribute writer 的名字与 instance variable 的名字相同,结尾为 "=".
格式: 

def my_attribute=(new_value)

@my_attribute = new_value
end

attribute writer

定义:用于 get the value of an variable back

格式:

def my_attribute

@my_attribute
end

attribute accessor

可以用 

  • attr_writer :name
  • attr_reader :name
  • attr_accessor :name

代替 def 格式的代码,它们是 equivalent 的

转载于:https://www.cnblogs.com/FBsharl/p/10463251.html

你可能感兴趣的文章
python中的协程:greenlet和gevent
查看>>
AliCTF2014题目解析之<reverse-300>
查看>>
BroadcastReceive之ip拨号
查看>>
百度移动统计调用api教程,少进坑(82001错误)
查看>>
【BZOJ5074】[Lydsy十月月赛]小B的数字 数学
查看>>
使用Spring MVC统一异常处理实战
查看>>
leetcode-14 longest-common-prefix(最长公共前缀)
查看>>
轮询和长轮询
查看>>
C & C++
查看>>
RSA算法原理
查看>>
类对象序列化为json串,json串反序列化为类对象
查看>>
时事与网络流行
查看>>
伪随机数与采样(sampling)
查看>>
matlab 中使用 GPU 加速运算
查看>>
变量和数据结构的赋初值
查看>>
音乐的要素
查看>>
iOS引入JavaScriptCore引擎框架(二)
查看>>
绘图(CGcontext)
查看>>
CRM WEB UI 03搜索界面新建按钮调到详细界面
查看>>
wpa_supplicant安装
查看>>