tags:

views:

50

answers:

2

Hi,

I have a text file from which I want to create a Hash for faster access. My text file is of format (space delimited)

author title date popularity

I want to create a hash in which author is the key and the remaining is the value as an array.

created_hash["briggs"] = ["Manup", "Jun,2007", 10]

Thanks in advance.

+1  A: 

Just loop through each line of the file, use the first space-delimited item as the hash key and the rest as the hash value. Pretty much exactly as you described.

created_hash = {}
file_contents.each_line do |line|
  data = line.split(' ')
  created_hash[data[0]] = data.drop 1
end
Chuck
I did this.. wanted to know is there any faster way cause the files usually have lots of lines.IO.readlines can hold all the data and each value represents a line. Is there anyway simple way to map this in one step to a hash without iterating. Thanks.
Sainath Mallidi
+2  A: 
require 'date'

created_hash = File.foreach('test.txt', mode: 'rt', encoding: 'UTF-8').
reduce({}) {|hsh, l|
  name, title, date, pop = l.split
  hsh.tap {|hsh| hsh[name] = [title, Date.parse(date), pop.to_i] }
}

I threw some type conversion code in there, just for fun. If you don't want that, the loop body becomes even simpler:

  k, *v = l.split
  hsh.tap {|hsh| hsh[k] = v }

You can also use readlines instead of foreach. Note that IO#readlines reads the entire file into an array first. So, you need enough memory to hold both the entire array and the entire hash. (Of course, the array will be eligible for garbage collection as soon as the loop finishes.)

Jörg W Mittag
+1 for the use of Object#tap
Michael Kohl