潇洒读出2个不同的CSV

时间:2014-10-13 09:39:34

标签: ruby

大家好我正在尝试让我的仪表板正常工作,但我无法找到一种方法将值放入我的List Widget可以读取的内容中。

  begin
    id = 1
    names.each do |item| 
      label = names[id][0] #names = names.csv path
      value = host_status[id]['status'] #host_status = host_status.csv path
      items = { label: label, value: value }
      id += 1
    end
  rescue      
  end

  send_event('hosts', { items: items })

所以这个脚本应该做的是:

  • 使用从status.cgi(工作)获取的值写入host_status.csv

  • 遍历host_status.csv和names.csv,从两者中获取值

  • 输出应该是这样的(标签来自names.csv,值来自host_status.csv)=>

    {label:“localhost”,值:“UP”},{label:“USV”,值:“UP”}

列表小部件需要类似哈希中的数组,其中包含键标签和值,据我所知,但是我的脚本不会返回任何类似于哈希推送方法的内容吗?

1 个答案:

答案 0 :(得分:0)

我在这里假设名称是数组[['foo'], ['bar']]

的数组

并且host_status是一个对象数组[{'status' => 'foo'}, {'status' => 'bar'}]

你应该能够做到

names = [['foo'], ['bar']]
host_status = [{'status' => 'foo'}, {'status' => 'bar'}]
labels = names.map(&:first) # ['foo', 'bar']
values = host_status.map {|s| s['status'] } # ['foo', 'bar']

# zip zips together two arrays [['foo', 'foo'], ['bar', 'bar']]
# inject iterates over the array and returns a new data structure
items = labels.zip(values).inject([]) do |memo, (k,v)|
  memo.push({label: k, value:v})
  memo
end   

您应该能够在irb会话中运行该代码示例。

可枚举#地图:http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-map

可数#zip:http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-zip

可数#injection:http://www.ruby-doc.org/core-1.9.3/Enumerable.html#method-i-inject