0

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.

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.