添加到ruby类内部的现有哈希

添加到ruby类内部的现有哈希,ruby,Ruby,我正在尝试创建一个具有如下数据结构的哈希: hash = { :a => { :a1 => "x", :a2: => "x", :a3 => "x" }, :b => { :b1 => "x", :b2: => "x", :b3 => "x" }, } 类函数的内部。我对OO比较陌生,所以可能我没有正确理解变量的作用域 这是我的密码: class Foo # Control class args attr_accessor :

我正在尝试创建一个具有如下数据结构的哈希:

hash = { 
:a => { :a1 => "x", :a2: => "x", :a3 => "x" },
:b => { :b1 => "x", :b2: => "x", :b3 => "x" },    
 }
类函数的内部。我对OO比较陌生,所以可能我没有正确理解变量的作用域

这是我的密码:

class Foo
  # Control class args
  attr_accessor :site, :dir

  # Initiate our class variables
  def initialize(site,dir)
    @site    = site
    @dir = dir
    #@records = {}
    @records = Hash.new { |h, k| h[k] = Hash.new }
  end

  def grab_from_it
    line = %x[tail -1 #{@dir}/#{@site}/log].split(" ")
    time = line[0, 5].join(" ")
    rc   = line[6]
    host = line[8]
    ip   = line[10]
    file = line[12]

    @records = { "#{file}" => { :time => "#{time}", :rc => "#{rc}", :host => "#{host}", :ip => "#{ip}" } }
  end

end
主体:

foo = Foo.new(site,dir)

foo.grab_from_it

pp foo

sleep(10)

foo.grab_from_it

pp foo

它工作并成功地创建了一个具有所需结构的散列,但当我再次运行时,它会覆盖现有的散列。我希望它继续添加到其中,这样我就可以创建一个“running tab”。

替换下一行

@records={“{file}”=>{:time=>“{time}”、:rc=>“{rc}”、:host=>“{host}”、:ip=>“{ip}}”

@records[“#{file}”]={:time=>“#{time}”,:rc=>“#{rc}”,:host=>“#{host}”,:ip=>“#{ip}”
每次调用
@records={}
时,实例变量都指向一个新的散列。因此,
initialize
中的初始化代码无效。您应该使用
hash
[]=
实例方法将新条目添加到现有哈希,而不是用新的哈希替换初始化的哈希

顺便说一句,您可以使用
variable
引用字符串,而不是使用字符串插值
“#{variable}”
创建新的字符串

@records[file]={:time=>time,:rc=>rc,:host=>host,:ip=>ip}
如果希望哈希的第一层和第二层都具有更新行为,可以查看该方法

@records[file].update({:time=>time,:rc=>rc,:host=>host,:ip=>ip})

您希望在什么中添加什么?