Ruby中自定义class能否像Array定义[]=方法?怎么定义?

来源:百度知道 编辑:UC知道 时间:2024/09/20 06:51:30
如题。恳请Ruby行家出马指教。

class Test
def []=(key, value)
@status ||= []
@status << { key => value }
end

def [](key)
item = @status.find { |s| s.keys.first == key }
item[key]
end
end

t = Test.new
t["tom"] = 80
puts t["tom"] # 80

可以的。举个例子:

class Exp
attr :a
def initialize (a,b,c)
@a = a + b +c
end

def []= (index,*args)
self.a.index(index)
end

end

e = Exp.new('aaaa','bbbb','cccc')
puts e.a
puts e.[]=("b")

输出结果:
"aaaabbbbcccc"
4

不知道是不是你想要的答案,呵呵。

能。Ruby一切都是方法

def []=(other)
# ...
end