Tobyrrr00
Tobyrrr00

Reputation: 41

Ruby. Align Output to right AND left at the same time

I have this Hash

itemHash = {"124"=>["shoes", "59.99"],
            "456"=>["pants", "49.50"], 
            "352"=>["socks", "3.99"]}

I need to diplay it like this, with Description aligned to the left and Price to the right

Item    Description     Price
-----   --------------  -----
124     shoes           59.99
352     socks            3.99
456     pants           19.50

but when I try this code

itemHash.each do |a,b|
  print " #{a}     "
  b.each do |c,d|
    print ("%8s %5s" % [c,d])
  end
  puts
end

I get this

 Item    Description      Price
 ----    -----------      -----

 124        shoes         59.99
 456        pants         49.50
 352        socks          3.99

I've tried "print ("%8s %5-s" % [c,d])" and "print ("%-8s %5s" % [c,d])" but neither does it right. For some reason when I align the description (c) it automatically applies it to the price (d). Anything I'm missing here?

Upvotes: 0

Views: 160

Answers (1)

Chris Heald
Chris Heald

Reputation: 62648

Your b.each do |c,d| loop is actually yielding each item in the array and attempting to destructure what isn't there, so you get:

"%8s %5s" % ["shoes", nil]
"%8s %5s" % ["59.55", nil]

etc.

You just need to omit your inner loop:

itemHash.each do |a,b|
  print " #{a}     "
  print "%-8s %5s" % b
  puts
end

Or more simply:

itemHash.each {|a, b| puts format(" %-8s%-8s%5s", a, *b) }

Upvotes: 1

Related Questions