2012-11-11 31 views
-1

LocationListinitialize方法的可變value填充在管線014這些變化由線015的print語句中relected,但在線路016的return認爲散列仍然是空的(向右滾動以查看=>後的返回值)。紅寶石方法返回散列值作爲{}

def random_point 
    x = rand * 2.0 - 1.0 
    y = rand * 2.0 - 1.0 
    until x**2 + y**2 < 1.0 
    x = rand * 2.0 - 1.0 
    y = rand * 2.0 - 1.0 
    end 
    return [x, y] 
end 

class LocationList < Hash 
    def initialize(node_list) 
    value = {} 
    node_list.each {|node| value[node] = random_point } 
    print value 
    return value 
    end 
end 

z = ["moo", "goo", "gai", "pan"] 

LocationList.new(z) 
#=> {"moo"=>[0.17733298257484997, 0.39221824315332987], "goo"=>[-0.907202436634851, 0.3589265999520428], "gai"=>[0.3910479677151635, 0.5624531973759821], "pan"=>[-0.37544369339427974, -0.7603500269538608]}=> {} 

在全局函數做大致相同的東西產生了預期的返回值:

def foo(node_list) 
    value = {} 
    node_list.each {|node| value[node] = random_point } 
    return value 
end 

foo(z) 
#=> {"moo"=>[-0.33410735869573926, -0.4087709899603238], "goo"=>[0.6093966465651919, 0.6349767372996336], "gai"=>[0.718925625951371, -0.6726652512124924], "pan"=>[0.08604969147566277, -0.518636160280254]} 
+2

'initialize'方法不應返回任何值。而是將散列存儲在實例變量中,並在實例化對象後讀取它。 – toniedzwiedz

回答

5

你創建你在initialize方法調用value一個新的Hash,而不是初始化self。說明該在線:

class LocationList < Hash 
    def initialize(node_list) 
    # self is already a LocationList, which is a Hash 

    value={} 
    # value is now a new Hash 

    node_list.each {|node| value[node]=random_point} 
    # value now has keys set 

    return value 
    # value is now discarded 
    # LocationList.new returns the constructed object; it does not return 
    # the result of LocationList#initialize 
    end 
end 

試試這個:

class LocationList < Hash 
    def initialize(node_list) 
    node_list.each {|node| self[node]=random_point} 
    end 
end 
2

請注意,你不實際調用initialize,你打電話new,然後調用initializenew拋棄返回值initialize,而是始終返回剛創建的對象。這可以在the implementation of Class#new中看得很清楚。

既然你已經在哈希你想要的,不要創建另一個哈希(value),只需使用你在(self)!這會將您的initialize降低到:

def initialize(node_list) 
    node_list.each { |node| self[node] = random_point } 
end