-1

I have a file with multiple lines. In each line, there two words and a number, split by a comma - for example a, b, 1. It means that string A and string B have the key as 1. I wrote the below piece of code

File.open(ARGV[0], 'r') do |f1|  
  while line = f1.gets  
    puts line  
  end  
end  

i'm looking for an idea of how to split and copy the characters and number in such a way that the first two words have the last number as key in the hashmap.

4

1 回答 1

2

这对你有用吗?

hash = {}
File.readlines(ARGV[0]).each do |line|
     var = line.gsub(' ','').split(',')
     hash[var[2]] = var[0],var[1]
end

这将给出:

hash['1'] = ['a','b']

我不知道您是想将第一个存储为整数还是字符串,如果它是您要查找的整数,请var[2].to_i在存储之前执行。

稍微修改了您的代码,我认为这样更短,如果我有任何错误,请告诉我。

于 2013-05-22T21:51:20.053 回答