庄周梦蝶

生活、程序、未来
   :: 首页 ::  ::  :: 聚合  :: 管理

Ruby Tip:定义索引操作符

Posted on 2010-02-01 16:29 dennis 阅读(1037) 评论(2)  编辑  收藏 所属分类: 动态语言
    怎么让你对象跟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]

        注意方法签名。


评论

# re: Ruby Tip:定义索引操作符  回复  更多评论   

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:定义索引操作符  回复  更多评论   

2010-02-02 09:18 by dennis
@Kai Chen
yeath,it's really cool.

只有注册用户登录后才能发表评论。


网站导航: