From: "David A. Black" Date: 2008-09-28T22:00:19+09:00 Subject: Re: Merging hashes and having trouble with variable scope! Hi -- On Sun, 28 Sep 2008, Andy Pipes wrote: > Hi. > > Caveat: I'm just learning Ruby coming from some basic PHP programming. > > In the following I am aiming to peer into two tab-separated files with > some vegetable facts on them. In the first 'column' of each file there > are vegetable names, followed by the data. However, whilst some of the > vegetables have the same name, others do not. My ultimate aim is to take > the contents of each of these files, and merge them into a master file, > and for those vegetables that have data in both files to merge the data. > > So a line from file 1 might read: > > Watermelon 60-80 4-10 > > and one file two: > > Watermelon 1/2oz. 34 12-26 24-48 > > and in the masterfile I would want: > > Watermelon 60-80 4-10 1/2oz. 34 12-26 24-48. > > I have been trying unsuccessfully for the past two days to do this so > any help is greatly appreciated!!! :) > > Here's some sample code: Back at ya :-) Try this. I've changed key names just to fit things on single lines and make my code look even slicker than it is :-) You can change all that back, of course. The main thing is to absolutely not write that same splitting routine five times! I've syphoned it off into a method (and you could possibly even trim the arguments down if you automated the "min"/"max" parts). So, see if this helps as a starting point. It doesn't distinguish among different vegetables, but that could be added. @v = {} def split_or_double(string, key1, key2) @v[key1], @v[key2] = string.split(/-/) @v[key2] || @v[key1] end File.foreach("vegetables.txt") do |line| name, temp, germ_days = line.split split_or_double(temp, :temp_max, :temp_min) split_or_double(germ_days, :germ_days_max, :germ_days_min) end File.foreach("vegetables2.txt") do |line| name2, crop_yield, row_space, plant_space, harvest_days = line.split split_or_double(row_space, :min_row_space, :max_row_space) split_or_double(plant_space, :min_plant_space, :max_plant_space) split_or_double(harvest_days, :min_harvest, :max_harvest) end p @v David -- Rails training from David A. Black and Ruby Power and Light: Intro to Ruby on Rails January 12-15 Fort Lauderdale, FL Advancing with Rails January 19-22 Fort Lauderdale, FL * * Co-taught with Patrick Ewing! See http://www.rubypal.com for details and updates!