| 赞 | 62 |
| VIP | |
| 好人卡 | |
| 积分 | 65 |
| 经验 | |
| 最后登录 | 2025-2-24 |
| 在线时间 | 1275 小时 |
百合控
- 梦石
- 0
- 星屑
- 6548
- 在线时间
- 1275 小时
- 注册时间
- 2013-8-21
- 回帖
- 3522

|
发表于 2014-2-5 17:58:28
|
显示全部楼层
david_ng223 发表于 2014-2-5 17:42 
引用12樓第8行
可是我在94頁的教程中找不到一個=~,
表示我只知道=,==,+=,-=,*=,/=,%=,**=,!=,=的用法
恩……self === other
此方法多是是用于 case 判断句中。预设情况下与 Object#== 相同。在子类中进行归属检查时,可以根据情况重新定义。
[pre lang="ruby" line="1"]a = 0
puts "Instance variables a is a " +
case a
when :hello
"symbol hello"
when "hi"
"string hi"
when 1
"Integer 1"
when 0
"Integer 0"
else
"Something else"
end
#=>Instance variables a is a Integer 0
#依次调用===比较a与case后面的元素
#如果true 执行子句[/pre]
有时候我们的比较更特殊
有一个类[pre lang="ruby" line="1"]class I_AM_A_CLASS
attr_accessor :m, :n
end[/pre]如果有下列比较 返回值是false
[pre lang="ruby" line="1"]a = I_AM_A_CLASS.new
puts a == I_AM_A_CLASS.new
#=> false[/pre]于是我们这样[pre lang="ruby" line="1"]class I_AM_A_CLASS
def ===(other)
return false if self.class != other.class
self.m === other.m && self.n === other.n
end
end[/pre]
有这个比较[pre lang="ruby" line="1"]a = I_AM_A_CLASS.new
puts a == I_AM_A_CLASS.new
#=> false
puts a === I_AM_A_CLASS.new
#=> true[/pre] |
|