From: Clifford Heath Date: 2011-04-14T10:20:38+09:00 Subject: Re: Help on hashing multiple keys and values On 04/14/11 10:46, Adam Adam wrote: > There must be something I'm missing, when I run > > name_hash = Hash.new{|key, value| key[value] = []} > File.open("numbers_and_colors.txt").each do |file_line| > file_line.chomp! > line_parts = file_line.split(/\t/) > name_hash["#{line_parts[0]}"] = %W["#{line_parts[1]}"] > puts name_hash["2"] > end > > I end up with > "Blue" > "Blue" > "Green" > > I'm worried with the actual data this will be 100000 "Blue" and a > "Green". Thanks for the help. You shouldn't print the data until you finish processing the file. You don't need to use "#{some-string}" to make a string into a string, and I've no idea what you're attempting by using %W[...]. You didn't seem to understand or apply the pattern I suggested. Basically it says: Find this array in the hash (if it doesn't exist then initialize it with an empty array) and append this word to the array. Try the following program (which contains the data file), understand it, and if there's something you don't follow, come back and ask again. The output it gives is this: {1=>["Red"], 2=>["Blue", "Green"], 3=>["Red"]} If you want to arrange for the entries in each array to be unique, you'll need to add that somehow, this doesn't do it: name_hash = {} DATA.each do |file_line| line_parts = file_line.split(/\W+/) (name_hash[line_parts[0].to_i] ||= []) << line_parts[1] end p name_hash __END__ 1 Red 2 Blue 3 Red 2 Green