From: WJ Date: 2011-04-18T01:35:26+09:00 Subject: Re: Help on hashing multiple keys and values Adam Adam wrote: > I'm trying to create a hash with multiple values per key from a tab > delimited file. numbers_and_colors.txt example: > > 1 Red > 2 Blue > 3 Red > 2 Green > > What I need is a hash that has key 2 assigned to values Blue and Green. > Running what I have below just erases the previous key, so puts > name_hash["2"] would only show Green. Ruby example: > > name_hash = Hash.new > File.open("numbers_and_colors.txt").each do |file_line| > file_line.chomp! > line_parts = file_line.split(/\t/) > name_hash["#{line_parts[0]}"] = "#{line_parts[1]}" > > I need this in a hash, so is there another way to go about this? Thanks > in advance to any help, as you can probable tell I only started learning > Ruby recently. name_hash = {} name_hash.default = [] IO.foreach( "data2" ){|line| key, val = line.split name_hash[ key ] += [val] } p name_hash ==> {"1"=>["Red"], "2"=>["Blue", "Green"], "3"=>["Red"]}