Ruby Tip:定义索引操作符

    xiaoxiao2024-08-17  83

    怎么让你对象跟Array或者Hash一样,可以使用[ ]操作符来获取属性值或者赋值? 问题其实就是如何定义 index操作符,在Ruby中可以这样做: class  Message    def initialize     @props = Hash. new    end    def [](key)       @props[key]    end        def [] = (key,value)       @props[key] = value    end  end m = Message. new m[ 0 ] = 1 p m[ 0 ] m[:a] = " hello " p m[:a] 文章转自庄周梦蝶  ,原文发布时间2010-02-01 相关资源:敏捷开发V1.0.pptx
    最新回复(0)