Ronan
Ronan

Reputation: 21

Ruby hashes. How to display each key as a table on screen?

I do have a hash like this.

v_cp={"29000"=>["Quimper"],
"29100"=>["Douarnenez",
"Kerlaz",
"Le Juch",
"Pouldergat",
"Poullan-sur-Mer"],
"29120"=>["Combrit",
"Plomeur",
"Saint Jean Trolimon","Pont-L\'Abbe","Tremeoc"],
"29140"=>["Melgven","Rosporden","Tourch"]

I would like to print out each key as a table format on screen like this : enter image description here

I use :

v_cp.each_key{|k| puts "*"+k+"*";} 

But of course I get this output:

enter image description here

which is not what I aim to...

I thought of sprintf or printf but I'm really lost here...

Any help ? Thanks

Upvotes: 0

Views: 332

Answers (2)

BobRodes
BobRodes

Reputation: 6165

You can use #print instead of #puts to put line feeds exactly where you want them. Unlike #puts, which automatically adds a new line every time it's called, #print prints out only the string that is passed to it, so you have to specifically print a new line character to get a new line.

For example, to get five keys that are the same size on each row, as in your first image:

example = {
  29000 => ['Bonjour'],
  29100 => ['Ça va?'],
  29200 => ['Hello'],
  29300 => ['Doing ok?'],
  29400 => ['Some text'],
  29500 => ['Something else'],
  29600 => ['More stuff'],
  29700 => ['This'],
  29800 => ['That'],
  29900 => ['The other']
}

example.keys.each_with_index do |key, index|
  print key.to_s
  print ((index + 1) % 5).zero? ? "\n" : '  '
end

# Result:
=begin
29000  29100  29200  29300  29400
29500  29600  29700  29800  29900
=end

(I liked two spaces better than one.)

If the length varies, you can use #ljust to pad smaller strings with trailing spaces, as Fizvlad mentions.

Consider preferring #print over #puts to output anything more complex than a simple string. You often can do with one call to #print what can take multiple calls to #puts, so overall #print is more efficient.

Upvotes: 0

Fizvlad
Fizvlad

Reputation: 136

If the length of each key is fixed you can just slice keys into subgroups and print them out:

v_cp.keys.each_slice(5) { |a| puts a.join(' ') }

If the length can vary, you should also ljust strings:

str_length = 6
v_cp.keys.each_slice(5) do |a|
  puts a.map { |e| e.ljust(str_length , ' ') }.join(' ')
end

Upvotes: 1

Related Questions