Hello to all,

HAving a hash where its keys are associated with arrays like below:

myHash = {"A"=>["HYU"], "B"=>["TU6"], "C"=>["11", "09","88","2"], "D"=>["01", "11"]}

Each key represent one header and the arrays elements represent the values for each header.

How to print each key in different column separated by comma "," and below each header print all the values of
corresponding array. Since some arrays have more elements, for the arrays that have less elements print blank
like below.

A,B,C,D
HYU,TU6,11,1
,,9,11
,,8,
,,2,

Thanks in advance for any help.

Recommended Answers

All 4 Replies

You can get the keys of a hash with hash.keys.

puts hash.keys.join ','
hash.keys.size.times do |i|
   s = hash.collect { |h| 
      # fill the entry (h[1]) as you'd like
      h[1][i] 
   }.join ','
   puts s
end

Hello L7Sqr,

Thanks for answer.

May you explain how it works your code. I undertand that "hash.keys.size" counts how many keys exist inside the hash (in this case 4) and "times" is the way to say loop 4 times. But I don't undertand clearly how "hash.collect" method works yet.

Besides this, I've done a little change to key "C" adding a new element, but this time I still getting the same output as for the original hash.

I.ve modified the hash like this (added "5" as last element in "C"):

hash = {"A"=>["HYU"], "B"=>["TU6"], "C"=>["11", "09","88","2","5"], "D"=>["01", "11"]}

And the output I receive is the same:

A,B,C,D
HYU,TU6,11,01
,,09,11
,,88,
,,2, 

When the output expected is:

A,B,C,D
HYU,TU6,11,01
,,09,11
,,88,
,,2, 
,,5,

How to fix this?

Thanks in advance.

It depends on how you are extending the array in the inner loop; how you have this coded is important and helpful in answering correctly.

Besides, I'm not sure what you are trying to do makes any sense. For your goals it might be better to choose another representation for the data. For example, if a hash is too limiting try using a struct or class to build specifically what you need.

Your process seems overly complicated.

I am guessing that your goal is to represent a hash in tabular format for writing into a data file (i.e. CSV). If this is a one time use or a dirty quick convertion project, you don't need to look for an elegant solution.

However, if you want to use L7Sqr solution, the only thing you need to update is to find the maximum size of array, which is the value of each key. Then use the number for your iteration. Currently, the script is using the hash key's size which is why it displays up to the 4th element.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.