中关村村草 发表于 2012-03-01 19:30

Eloquent Ruby 读书笔记 续

Eloquent Ruby 读书笔记 续




initializeruby
运算符重载和Ruby风格的运算符重载
程序大概意思是,重新定义,文件类的比较方法。只要目录和文件名一样,就说这两个文件类一样。ruby的
Ruby代码class DocumentPointer   
attr_reader :folder, :name
def initialize( folder, name )   
    @folder = folder   
    @name = name   
end
def ==(other)   
    return true if other.equal?(self)   
    return false unless other.instance_of?(self.class)   
    folder == other.folder && name == other.name   
end
end

class DocumentPointer
attr_reader :folder, :name
def initialize( folder, name )
    @folder = folder
    @name = name
end
def ==(other)
    return true if other.equal?(self)
    return false unless other.instance_of?(self.class)
    folder == other.folder && name == other.name
end
endRuby代码class DocumentPointer   
attr_reader :folder, :name
def initialize( folder, name )   
    @folder = folder   
    @name = name   
end
def ==(other)   
    return false unless other.respond_to?(:folder)   
    return false unless other.respond_to?(:name)   
    folder == other.folder && name == other.name   
end
end

class DocumentPointer
attr_reader :folder, :name
def initialize( folder, name )
    @folder = folder
    @name = name
end
def ==(other)
    return false unless other.respond_to?(:folder)
    return false unless other.respond_to?(:name)
    folder == other.folder && name == other.name
end
end当我们用的时候
Ruby代码#Asymmetry   
class ContractIdentifier < DocumentIdentifier   
end

doc_id = DocumentIdentifier.new( 'contracts', 'Book Deal' )   
con_id = ContractIdentifier.new( 'contracts', 'Book Deal' )   

puts "They are equal!" if doc_id == con_id

#Asymmetry
class ContractIdentifier < DocumentIdentifier
end

doc_id = DocumentIdentifier.new( 'contracts', 'Book Deal' )
con_id = ContractIdentifier.new( 'contracts', 'Book Deal' )

puts "They are equal!" if doc_id == con_id会出现子类没有父类方法的问题,在contractIdentifier里没有重载操作符。那么

Ruby代码class VersionedIdentifier < DocumentIdentifier   
attr_reader :version

def initialize(folder, name, version)   
    super(folder, name)   
    Well-Behaved Equality 147   
    @version = version   
end

def ==(other)   
    if other.instance_of? VersionedIdentifier   
      other.folder == folder &&   
      other.name == name &&   
      other.version == version   
    elsif other.instance_of? DocumentIdentifier   
      other.folder == folder && other.name == name   
    else
      false
    end
end
end

小忻黑夜 发表于 2012-03-01 22:36

谢谢分享
页: [1]
查看完整版本: Eloquent Ruby 读书笔记 续