From: Clifford Heath Date: 2011-04-14T08:40:34+09:00 Subject: Re: Help on hashing multiple keys and values On 04/14/11 09:33, 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. The idiom I use is to add an array to hold the values, like this: (name_hash[key] ||= []) << value Clifford Heath.