From: "SHULTZ,BARRY (HP-Israel,ex1)" Date: 2001-08-16T14:22:47+09:00 Subject: [ruby-talk:19859] RE: how to speed up hash script? Hi, > -----Original Message----- > From: gerry@ucar.edu [mailto:gerry@ucar.edu] > Sent: Wednesday, August 15, 2001 8:33 PM > class Climo > def initialize(in_file) > # Read in data > @fp = File.new(in_file, "r") > @lines = @fp.readlines() > @fp.close() > @num_lines = @lines.size() > @date_format = "YYMMDDHH" > @len_date = @date_format.size() > > # Store line indices in dictionary based on date field > @dict = Hash.new() > for i in 1...@num_lines > @dict[@lines[i][0...@len_date]] = i > end > > first_date = @lines[1][0...@len_date] > last_date = @lines[@num_lines-1][0...@len_date] > puts "first_date: ", first_date > puts "last_date: ", last_date > end > > On my machine this is running slightly faster than your script and it's shorter code. If you're willing and able to trade your @dict Hash for an Array. At least it makes sense for the piece of code you sent. Here I'm trying to take advantage of Enumerable#collect . @date_format = "YYMMDDHH" @len_date = @date_format.size() @dict = File.open(in_file,"r").collect{ |line| line[0...@len_date] } first_date = @dict[1] last_date = @dict[@dict.size - 1] puts "first_date: ", first_date puts "last_date: ", last_date My 0.02. Barry