From: ES Date: 2005-10-12T05:16:18+09:00 Subject: Re: Ruby noob with a coming from Python question Jeff Carlson wrote: > I am very new to ruby and thought I would start with my simplest python > script and port it over and along the way, learn the "ruby way" of doing > things. My solution so far is unsatisfactory and long. If you have any > suggestions, most especially about the "ruby way" to write the file2Map > method, I would appreciate it and all of my future ruby programs would > also appreciate it. > > Cheers, > Jeff Carlson > > ------------------------------------------------------------- > #!/usr/bin/python > # print statistics for seti@home jobs > from mx.DateTime import TimeDelta > import sys > > # this method takes a file with key/value pairs, seperated by "=" > # and makes a map of the file, keys and values, the length of the > # map is the length of the file > def getMapFromFile(fname): > lines = open(fname).readlines() > return dict([line.split("=") for line in lines]) This should work: def map_from(file) Hash[*File.readlines(file).map {|line| line.split '='}.flatten] end Broken down, File.readlines makes an Array of lines in the file; we then #map it to split each line into the two parts and then #flatten the Array from [[key1, val1], [key2, val2]] to [key1, val1, key2, val2]. This syntax can be used by Hash[], so we just 'splat' the Array to individual values by using the * operator. > # make maps of the two files > sMap = getMapFromFile(sys.argv[1]) > uMap = getMapFromFile(sys.argv[2]) > > prog = float(sMap["prog"].strip())*100 > et = TimeDelta(seconds=float(sMap["cpu"].strip())) > > #print results > print '%.2f%c completed in %d:%02d:%02d' % (prog, '%', et.hour, / > et.minute, et.second) > print 'units of work so far %s' % (uMap["nresults"].strip()) E