将 CSV 数据导入 ruby 数组/变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8466667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Importing CSV data into a ruby array/variable
提问by IMcD23
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.
我正在尝试将 CSV 用作 SiriProxy 项目插件中的设置文件,以使用局域网唤醒。这个项目是基于红宝石的。
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. 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.
所以我想要发生的是,例如,当变量 userAction 是“桌面”时,然后我查询 CSV 并将 MAC 地址返回到另一个变量中。我不知道如何做到这一点。我见过 csv 和 fast_csv,但不知道如何让它们像这样工作。
Thanks in advance!
提前致谢!
回答by David Grayson
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.
如果您尝试在 Ruby 1.9 中使用 FasterCSV,则会收到一条警告,指出标准 Ruby 1.9 CSV 库实际上更快。所以我使用了标准的 Ruby CSV 库。这应该适用于 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 文件。
回答by steenslag
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 => ', '})

