Ruby:如何在一个块中使用各自的文本文件名创建多个哈希值

时间:2015-02-18 15:43:13

标签: ruby

我想在多行文件的每一行(例如3个文件)中读取自己的哈希值。

这很容易作为三个单独的块:

cheap = Hash.new {|name, id| name[id] = ''}
File.open("cheap.txt", "r").each_line do |line|
  name, id = line.split(":")
  cheap[name] << id
end
cheap = cheap.sort_by{|k,v| v}

expensive = Hash.new {|name, id| name[id] = ''}
File.open("expensive.txt", "r").each_line do |line|
  name, id = line.split(":")
  expensive[name] << id
end
expensive = expensive.sort_by{|k,v| v}

auction = Hash.new {|name, id| name[id] = ''}
File.open("auction.txt", "r").each_line do |line|
  name, id = line.split(":")
  auction[name] << id
end
auction = auction.sort_by{|k,v| v}

但是本着“干”(不要重复自己)的精神,我试图在一个街区写这个。我谷歌并阅读了一些不同的方法,我接近的最好的比喻是“需要”设置如下:

%w{rubygems daemons eventmachine}.each { |x| require x }

但是,如果我尝试将此应用于我的谜题,我会遇到尝试使用我已分配给它的变量创建哈希名称的问题:

%w{cheap.txt expensive.txt auction.txt}.each do |x|
    x = Hash.new {|name, id| name[id] = ''}
    File.open(x, 'r').each_line do |l|
        name, id = line.split(':')
        x.split(".")[name] << id
    end
end

这显然会输出我正在尝试将字符串转换为哈希的错误。如何将三个单独文件中的每一行拉入自己的哈希对象?现在我将使用三个独立的块,但从概念上讲,我对此非常好奇。

1 个答案:

答案 0 :(得分:1)

有很多选择。最简单且最接近您尝试实现的是将哈希存储在哈希中:

items = {}

%w{cheap.txt expensive.txt auction.txt}.each do |x|
    items[x] = Hash.new {|name, id| name[id] = ''}
    File.open(x, 'r').each_line do |l|
        name, id = line.split(':')
        items[x][name] << id
    end
end

或者,将实际加载包装在函数中,该函数接受文件名:

def load_file(filename)
  data = Hash.new {|name, id| name[id] = ''}
  File.open("expensive.txt", "r").each_line do |line|
    name, id = line.split(":")
    data[name] << id
  end
  data.sort_by{|k,v| v}
end

cheap = load_file('cheap.txt')
expensive = load_file('expensive.txt')
auction = load_file('auction.txt')