将CSV数据导入ruby数组/变量 [英] Importing CSV data into a ruby array/variable

查看:173
本文介绍了将CSV数据导入ruby数组/变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在插件中使用CSV作为设置文件,使SiriProxy项目使用wake-on-lan。这个项目是基于ruby的。



所以csv如下:

  Name,MACAddress 
Desktop,01-23-45-67-89-ab
Computer,02-46-81-02-46-cd



等等...



所以我想发生的是,例如,变量userAction是Desktop,然后我查询CSV,并将MAC地址返回到另一个变量。我迷失在如何做到这一点。我已经看到了csv和faster_csv,但不知道如何让这些工作像这样。



提前感谢!

解决方案

如果你尝试在Ruby 1.9中使用FasterCSV,你会得到一个警告,标准的Ruby 1.9 CSV库实际上更快。所以我使用标准的Ruby CSV库。这应该在Ruby 1.9或1.8.7中工作。

  require'csv'

模块MyConfig
@mac_address_hash = {}
CSV.foreach(config.csv)do | row |
name,mac_address = row
next if name ==Name
@mac_address_hash [name] = mac_address
end

现在我们有这个哈希:+ @ mac_address_hash.inspect

def self.mac_address(computer_name)
@mac_address_hash [computer_name]
end

end

输入桌面的MAC地址:+ MyConfig.mac_address(Desktop)

这段代码的输出是:

 现在我们有了这个哈希:{Computer=>02-46- 81-02-46-cd,Desktop=>01-23-45-67-89-ab} 
桌面的MAC地址:01-23-45-67-89-ab

现在我想让你做的是仔细阅读这段代码的每一行,并尝试理解它的作用以及为什么有必要。



您可以改进此代码,以便在第一次需要时加载CSV文件。


I am trying to use a CSV as a settings file in a plugin for the SiriProxy project to use wake-on-lan. This project is based on ruby.

So the csv is as follows:

Name, MACAddress
Desktop, 01-23-45-67-89-ab
Computer, 02-46-81-02-46-cd

and so on...

So what I would like to happen is that when the variable userAction is "Desktop" for instance, then I query the CSV and it returns the MAC address into another variable. I am lost on how to do this. I have seen the csv and faster_csv but do not know how to get those to work like this.

Thanks in advance!

解决方案

If you try to use FasterCSV in Ruby 1.9 you get a warning saying that the standard Ruby 1.9 CSV library is actually faster. So I used the standard Ruby CSV library. This should work in Ruby 1.9 or 1.8.7.

require 'csv'

module MyConfig
  @mac_address_hash = {}
  CSV.foreach("config.csv") do |row|
    name, mac_address = row
    next if name == "Name"
    @mac_address_hash[name] = mac_address
  end

  puts "Now we have this hash: " + @mac_address_hash.inspect

  def self.mac_address(computer_name)
    @mac_address_hash[computer_name]
  end

end

puts "MAC address of Desktop: " + MyConfig.mac_address("Desktop")

The output of this code is:

Now we have this hash: {"Computer"=>" 02-46-81-02-46-cd", "Desktop"=>" 01-23-45-67-89-ab"}
MAC address of Desktop:  01-23-45-67-89-ab

Now what I want you to do is read every line of this code carefully and try to understand what it does and why it is necessary. This will make you a better programmer in the long run.

You could improve this code to lazily load the CSV file the first time it is required.

这篇关于将CSV数据导入ruby数组/变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆