Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.ruby > #3064
| From | "WJ" <w_a_x_man@yahoo.com> |
|---|---|
| Newsgroups | comp.lang.ruby |
| Subject | Re: Help on hashing multiple keys and values |
| Date | 2011-04-17 16:30 +0000 |
| Organization | NewsGuy - Unlimited Usenet $19.95 |
| Message-ID | <iof4ih0qu7@enews2.newsguy.com> (permalink) |
| References | <e7079548e51ac6677d70c58dba0b2fd3@ruby-forum.com> |
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"]}
Back to comp.lang.ruby | Previous | Next — Previous in thread | Find similar | Unroll thread
Help on hashing multiple keys and values Adam Adam <adam_sateriale@yahoo.com> - 2011-04-13 18:33 -0500
Re: Help on hashing multiple keys and values Clifford Heath <no@spam.please.net> - 2011-04-14 09:36 +1000
Re: Help on hashing multiple keys and values jake kaiden <jakekaiden@yahoo.com> - 2011-04-13 18:59 -0500
Re: Help on hashing multiple keys and values Adam Adam <adam_sateriale@yahoo.com> - 2011-04-13 19:46 -0500
Re: Help on hashing multiple keys and values Clifford Heath <no@spam.please.net> - 2011-04-14 11:15 +1000
Re: Help on hashing multiple keys and values jake kaiden <jakekaiden@yahoo.com> - 2011-04-13 21:05 -0500
Re: Help on hashing multiple keys and values jake kaiden <jakekaiden@yahoo.com> - 2011-04-13 20:37 -0500
Re: Help on hashing multiple keys and values Adam Adam <adam_sateriale@yahoo.com> - 2011-04-13 21:13 -0500
Re: Help on hashing multiple keys and values "WJ" <w_a_x_man@yahoo.com> - 2011-04-17 16:30 +0000
csiph-web