简体   繁体   English

将CSV数据导入ruby数组/变量

[英]Importing CSV data into a ruby array/variable

I am trying to use a CSV as a settings file in a plugin for the SiriProxy project to use wake-on-lan. 我正在尝试使用CSV作为SiriProxy项目插件中的设置文件来使用wake-on-lan。 This project is based on ruby. 这个项目基于ruby。

So the csv is as follows: 所以csv如下:

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. 所以我想要发生的是,例如当变量userAction是“桌面”时,我查询CSV并将MAC地址返回到另一个变量。 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. 我见过csv和faster_csv,但不知道如何让这些工作像这样。

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. 如果您尝试在Ruby 1.9中使用FasterCSV,则会收到警告,说标准的Ruby 1.9 CSV库实际上更快。 So I used the standard Ruby CSV library. 所以我使用了标准的Ruby CSV库。 This should work in Ruby 1.9 or 1.8.7. 这应该适用于Ruby 1.9或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文件。

I'll demonstrate the dirt-simple method. 我将展示简单易懂的方法。 Stuffing everything in a hash as David Grayson did is far more efficient in the long run, but for a run-a-few-times script this might be sufficient. 像David Grayson那样在哈希中填充所有内容从长远来看效率要高得多,但是对于几次运行的脚本来说这可能就足够了。

require 'csv'
config = CSV.read('config.csv')
config.shift # Get rid of the header
# We're done! Start using like so:
p config.assoc("Computer").last #=>" 02-46-81-02-46-cd" 

If the leading space is unwanted: 如果领先的空间是不需要的:

config = CSV.read('config.csv', {:col_sep => ', '})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM