Q:

Problem with initializing a hash in ruby

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.

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.)

