美文网首页
Ruby值对象

Ruby值对象

作者: chenge微博谈 | 来源:发表于2015-09-04 20:40 被阅读61次

    实例代码

    class EmailAddress
      include Comparable
    
      def initialize(string)
        if string =~ /@/
          @raw_email_address = string.downcase.strip
        else
          raise ArgumentError, "email address must have an '@'"
        end
      end
    
      def <=>(other)
        raw_email_address <=> other
      end
    
      def to_s
        raw_email_address
      end
    
      protected
    
      attr_reader :raw_email_address
    end
    

    调用代码

    $ irb>> require "./email_address" #=> true
    >> EmailAddress.new("user@example.com") == "user@example.com" #=> false (would have previously been true)
    >> EmailAddress.new("user@example.com") == EmailAddress.new("user@example.com") #=> true
    

    相关文章

      网友评论

          本文标题:Ruby值对象

          本文链接:https://www.haomeiwen.com/subject/ynwlcttx.html