返回哈希值为{}的Ruby方法

返回哈希值为{}的Ruby方法,ruby,hash,return,instantiation,Ruby,Hash,Return,Instantiation,LocationList初始化方法中的变量值填入第014行。这些更改由第015行中的print语句发布,但第016行中的返回认为哈希仍然为空,请向右滚动查看=>之后的返回值 您正在创建一个在initialize方法中调用value的新哈希,而不是初始化self。说明这一点: class LocationList < Hash def initialize(node_list) # self is already a LocationList, which is a Hash

LocationList初始化方法中的变量值填入第014行。这些更改由第015行中的print语句发布,但第016行中的返回认为哈希仍然为空,请向右滚动查看=>之后的返回值


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

请注意,您实际上并没有调用initialize,而是调用initialize。new丢弃initialize的返回值,而总是返回刚刚创建的对象。这一点在中国可以相当清楚地看到

因为你已经在你想要的散列中,所以不要再创建另一个散列值,只需使用你自己的散列值!这会将您的初始化减少到:

initialize方法不应返回任何值。将哈希存储在实例变量中,并在实例化对象后读取它。
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
def initialize(node_list)
  node_list.each { |node| self[node] = random_point }
end