我有3个数组,我试图并行打印相应的字符串。 Ruby的新手。不确定我是否应该连接?我真的很想创建一张桌子,但我不知道怎么做。
我目前的代码:
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]
输出如下:
Buffy Summers 17 Blonde
Willow Rosenberg 16 Red
Xander Harris 18 Brown
我真的很喜欢他们对齐。我意识到我也应该循环。我是初学者。
我想要输出:
Buffy Summers 17 Blonde
Willow Rosenberg 16 Red
Xander Harris 18 Brown
答案 0 :(得分:0)
要获得所需的对齐方式,请访问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
答案 1 :(得分:0)
假设您的数据包含在以下四个数组中。
name = ["Buffy Summers", "Willow Rosenberg", "Xander Harris", "Granny", "Lucy"]
age = ["17", "16", "18", "101", "7"]
hair_color = ["blonde", "red", "brown", "white", "purple"]
col_fmt = [{justify: :L, pad: 4}, {justify: :R, pad: 2}, {justify: :L, pad: 3}]
然后你可以按照以下方式打印。
arr = [name, age, hair_color]
columns = col_fmt.zip(arr.map { |a| a.max_by(&:size).size }).
map { |h, sz| h.merge(width: sz) }
#=> [{:justify=>:L, :pad=>4, :width=>16}, {:justify=>:R, :pad=>2, :width=>3},
# {:justify=>:L, :pad=>3, :width=>6}]
arr.transpose.each do |a|
a.zip(columns).each do |attr, fmt|
print ' ' * fmt[:pad]
print fmt[:justify] == :L ? attr.ljust(fmt[:width]) : attr.rjust(fmt[:width])
end
puts
end
# Buffy Summers 17 blonde
# Willow Rosenberg 16 red
# Xander Harris 18 brown
# Granny 101 white
# Lucy 7 purple
答案 2 :(得分:0)
请执行以下操作
name = ["Buffy Summers", "Willow Rosenberg", "Xander Harris"]
age = ["17", "16", "18"]
hair_color = ["blonde", "red", "brown"]
name.count.times do | index |
put“#{name [index]}#{age [index]}#{hair_color [index]}”
<删除>端德尔>
name.count.times do |index|
printf "%-20s %-2s %-10s\n", name[index],age[index] , hair_color[index]
end