0

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

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

它可以工作并成功创建具有我想要的结构的哈希,但是当我再次运行时,它会覆盖现有的哈希。我希望它不断添加,所以我可以创建一个“运行选项卡”。

4

1 回答 1

2

替换以下行

@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 }

如果您想要哈希的第一层和第二层的UPDATE行为,您可以查看该Hash#update方法。

@records[file].update({ :time => time, :rc => rc, :host => host, :ip => ip })
于 2013-06-05T13:04:48.567 回答