2013-10-28 17 views
0

我瞭解Ruby的語法糖是如何讓我們的值賦給一個變量這樣效仿Ruby的索引訪問,[]

o = ExampleClass.new 
o.name = "An object" 

ExampleClass有一個方法:

name=(new_name) 

這是如何工作的對於像Hash這樣的課程?如果我想要這樣做,我會如何命名我的方法?

h = MyHash.new 
h[:key] = value 

我不是繼承Hash類。

回答

3

你只需有方法

def [](key_to_retrieve) 
    #return corresponding value here 
end 

def []=(key_to_set, value_to_set) 
    #set key/value here 
end 
+0

謝謝!! Ruby is awesome –

+0

@ x-treme請記住,您可以「接受」此答案來獎勵回答者,並讓其他用戶在將來知道此答案最能解決您的問題。 – Phrogz

+0

感謝@Phrogz的領導 –

1

JacobM幾乎回答了這個問題;但我想補充一點,我讀了一些關於可變類

您可能會覺得這很有趣。您可以定義一個可變類快速使用Struct爲:

MyHash = Struct.new(:x, :y) 
#This creates a new class MyHash with two instance variables x & y 
my_obj = MyHash.new(3, 4) 
#=> #<struct MyHash x=3, y=4> 
my_obj[:x] = 10 
#=> #<struct MyHash x=10, y=4> 
my_obj.y = 11 
#=> #<struct MyHash x=10, y=11> 

這將自動實例變量可讀可變通過[]=

您可以隨時打開類添加一些新的東西;

class MyHash 
    def my_method 
    #do stuff 
    end 
    def to_s 
    "MyHash(#{x}, #{y})" 
    end 
end