2011-02-04 90 views

回答

3

也許我不明白的問題,但

>> class Hash 
.. alias :foobar :[]= 
..  end 
=> nil 
>> h = Hash.new 
=> {} 
>> h.foobar(:a, 1) 
=> 1 
>> h 
=> {:a=>1} 
+0

謝謝你的伎倆。我沒有想過把它作爲一個符號:) – 2011-02-04 10:53:17

+0

冒號方括號表示法有什麼作用? :[] = <---那。 – Danny 2012-07-29 22:22:30

3

別名接受的符號作爲參數,因此,這裏是你想要做什麼的例子:

class Toto 
    def initialize 
    @t = {} 
    end 

    def []=(k,v) 
    @t[k] = v 
    end 

    alias assign :[]= 
end 

t = Toto.new 

t[1] = 5 
t.assign(3, 4) 

puts t.inspect 

顯示:#<Toto:0x29b8318 @t={1=>5, 3=>4}>

另外,你得到的別名參數順序錯了,它是alias new_name old_name