morrime morrime - 4 months ago 43
Ruby Question

Ruby: How to print strings from arrays in parallel

I have 3 arrays and I'm trying to print the respective strings in parallel. Very new to Ruby. Not sure if I should be concatenating? I'd really like to create a table, but I have no idea how.

My current code:

name = ["Buffy Summers", "Willow Rosenberg", "Xander Harris"]
age = ["17", "16", "18"]
hair_color = ["blonde", "red", "brown"]

print name[0]
print " "
print age[0]
print " "
puts hair_color[0]

print name[1]
print " "
print age[1]
print " "
puts hair_color[1]

print name[2]
print " "
print age[2]
print " "
puts hair_color[2]


Output looks like this:

Buffy Summers 17 Blonde
Willow Rosenberg 16 Red
Xander Harris 18 Brown


I'd really like them to align. I realize that I also should be looping. I'm a beginner.

I want the output to read:

Buffy Summers 17 Blonde
Willow Rosenberg 16 Red
Xander Harris 18 Brown

Answer

To get the aligning as you want, more information at String#%.

max = name.group_by(&:length).max.first

name.zip(age, hair_color).each do |name, age, hair_color|
  puts "%-#{max}s %s %s" % [name, age, hair_color]
end

=> Buffy Summers    17 blonde
=> Willow Rosenberg 16 red
=> Xander Harris    18 brown