0

方法中的变量填充value在第 014 行。这些更改由第015 行的语句反映,但第016 行认为哈希仍然为空(向右滚动查看返回值之后)。initializeLocationListprintreturn=>

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]}
4

2 回答 2

7

您正在创建一个valueinitialize方法中调用的新 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
于 2012-11-11T01:11:28.960 回答
2

请注意,您实际上并不是在调用initialize,而是在调用new,然后调用initializenew丢弃 的返回值initialize,而总是返回刚刚创建的对象。这一点在实施中Class#new可以看得很清楚。

由于您已经在所需的哈希中,因此不要创建另一个哈希 ( value),只需使用您所在的哈希 ( ) 即可self!这将您减少initialize到:

def initialize(node_list)
  node_list.each { |node| self[node] = random_point }
end
于 2012-11-11T01:11:40.807 回答