Ruby方法返回哈希值为{}

时间:2012-11-11 00:55:28

标签: ruby hash return instantiation

value initialize方法中的变量LocationList填充在第014行。这些更改由第015行中的print语句重新选择,但是{{{行016中的1}}认为哈希值仍为空(向右滚动以查看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]}=> {}

2 个答案:

答案 0 :(得分:5)

您正在创建一个新的哈希,在value方法中调用initialize,而不是初始化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

答案 1 :(得分: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