From: Logan Capaldo Date: 2005-10-12T05:21:50+09:00 Subject: Re: Ruby noob with a coming from Python question On Oct 11, 2005, at 4:06 PM, Jeff Carlson wrote: > Oops, I meant the *getMapFromFile* function. If I could see the > ruby way of writing a method to take a file of the form > key1=value1 > key2=value2 > etc > and easily make it into a hash in a concise way (as in the python > example) that would be great. > > 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]) >> # 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()) >> > > results = File.open(file_name) do |file| file.map { |line| line.chomp.split(/=/)[0..1] } end.inject({}) { |results, (key, val)| results[key] = val; results } ...OR... results = {} File.open(file_name) do |file| file.each do |line| line.chomp! key, val = line.split(/=/) results[key] = val end end results