Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I assign multiple values to a hash key?

Tags:

ruby

hash

For the sake of convenience I am trying to assign multiple values to a hash key in Ruby. Here's the code so far

myhash = { :name => ["Tom" , "Dick" , "Harry"] }

Looping through the hash gives a concatenated string of the 3 values

Output:

name : TomDickHarry

Required Output:

:name => "Tom" , :name => "Dick" , :name => "Harry"

What code must I write to get the required output?

like image 727
Anand Shah Avatar asked Nov 06 '09 13:11

Anand Shah


People also ask

Can a hash key have multiple values?

Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.

Can a Key have multiple values Ruby?

Can a key have multiple values Ruby? Multiple Values For One Key Words are unique, but they can have multiple values (definitions) associated with them.

What is key and value in hash?

A hash table is a type of data structure that stores key-value pairs. The key is sent to a hash function that performs arithmetic operations on it. The result (commonly called the hash value or hash) is the index of the key-value pair in the hash table.


2 Answers

myhash.each_pair {|k,v| v.each {|n| puts "#{k} => #{n}"}}
#name => Tom
#name => Dick
#name => Harry

The output format is not exactly what you need, but I think you get the idea.

like image 64
pierrotlefou Avatar answered Sep 22 '22 21:09

pierrotlefou


The answers from Rohith and pierr are fine in this case. However, if this is something you're going to make extensive use of it's worth knowing that the data structure which behaves like a Hash but allows multiple values for a key is usually referred to as a multimap. There are a couple of implementations of this for Ruby including this one.

like image 44
mikej Avatar answered Sep 21 '22 21:09

mikej