莊周夢(mèng)蝶

          生活、程序、未來(lái)
             :: 首頁(yè) ::  ::  :: 聚合  :: 管理

          Ruby Tip:定義索引操作符

          Posted on 2010-02-01 16:29 dennis 閱讀(1056) 評(píng)論(2)  編輯  收藏 所屬分類: 動(dòng)態(tài)語(yǔ)言
              怎么讓你對(duì)象跟Array或者Hash一樣,可以使用[ ]操作符來(lái)獲取屬性值或者賦值? 問(wèn)題其實(shí)就是如何定義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]

                  注意方法簽名。


          評(píng)論

          # re: Ruby Tip:定義索引操作符  回復(fù)  更多評(píng)論   

          2010-02-02 00:08 by Kai Chen
          Actually, you can write these logic more simple with ActiveSupport:

          @@@
          class Message
          attr_accessor :props
          def initialize
          @props = Hash.new
          end
          delegate '[]', '[]=', :to => :props
          end

          msg = Message.new #=> #<Message:0x103f99530 @props={}>
          msg[:id] = 1
          msg[:id] #=> 1
          @@@

          Kinda cool, right?

          Rdoc: http://api.rubyonrails.org/classes/Module.html#M000110

          # re: Ruby Tip:定義索引操作符  回復(fù)  更多評(píng)論   

          2010-02-02 09:18 by dennis
          @Kai Chen
          yeath,it's really cool.
          主站蜘蛛池模板: 郯城县| 九江市| 台江县| 呼玛县| 益阳市| 巫山县| 东安县| 公安县| 措勤县| 垣曲县| 进贤县| 酉阳| 文山县| 普安县| 渭南市| 麻阳| 东丽区| 鸡西市| 阳新县| 梓潼县| 三台县| 确山县| 浏阳市| 五莲县| 佳木斯市| 长宁区| 永年县| 昌都县| 颍上县| 抚顺市| 香格里拉县| 军事| 区。| 宁阳县| 清涧县| 鲜城| 仙游县| 喀什市| 固镇县| 鱼台县| 白朗县|