| david_ng223 发表于 2014-2-5 17:42 ![]() 引用12樓第8行
 可是我在94頁的教程中找不到一個=~,
 表示我只知道=,==,+=,-=,*=,/=,%=,**=,!=,=的用法
恩……
 self === other 此方法多是是用于 case 判断句中。预设情况下与 Object#== 相同。在子类中进行归属检查时,可以根据情况重新定义。
 
 a = 0puts "Instance variables a is a " +case awhen :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 执行子句
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 执行子句 
 
 有时候我们的比较更特殊
 有一个类
 class I_AM_A_CLASS  attr_accessor :m, :nend
如果有下列比较 返回值是falseclass I_AM_A_CLASS 
  attr_accessor :m, :n 
end 
 a = I_AM_A_CLASS.new puts a == I_AM_A_CLASS.new#=> false
于是我们这样a = I_AM_A_CLASS.new 
  
puts a == I_AM_A_CLASS.new 
#=> false 
class I_AM_A_CLASS  def ===(other)    return false if self.class != other.class    self.m === other.m && self.n  === other.n  endend
class I_AM_A_CLASS 
  def ===(other) 
    return false if self.class != other.class 
    self.m === other.m && self.n  === other.n 
  end 
end 
有这个比较
 a = I_AM_A_CLASS.new puts a == I_AM_A_CLASS.new#=> false puts a === I_AM_A_CLASS.new#=> true
a = I_AM_A_CLASS.new 
  
puts a == I_AM_A_CLASS.new 
#=> false 
  
puts a === I_AM_A_CLASS.new 
#=> true 
 |