4

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!

4

2 回答 2

10

如果您尝试在 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")

这段代码的输出是:

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

现在我想让你做的是仔细阅读这段代码的每一行,并尝试理解它的作用以及为什么它是必要的。从长远来看,这将使您成为更好的程序员。

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

于 2011-12-11T19:32:44.917 回答
6

我将演示简单的方法。从长远来看,像 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" 

如果不需要前导空格:

config = CSV.read('config.csv', {:col_sep => ', '})
于 2011-12-11T20:37:38.193 回答