对同一行上的多个变量使用重复格式
Use repeat of format for many variables on the same line
puts "%-30s%2s%3d%2s%3d%2s%3d%2s%3d%2s%3d" % [tn,ln,a,ln,b,ln,c,ln,d,ln,e]
这是 Ruby,但许多语言都使用这种格式。我忘记了如何以相同的格式输出多个变量,而无需在每种情况下重复格式。在这里,我想要 5 个整数的“%3d%2s”,每个整数由“|”
分隔
你可以这样写。
def print_my_string(tn, ln, *ints)
fmt = "%-10s" + ("|#{"%2s" % ln}%3d" * ints.size) + "|"
puts fmt % [tn, *ints]
end
然后,例如,
print_my_string("hello", "ho", 2, 77, 453, 61, 999)
显示
hello |ho 2|ho 77|ho453|ho 61|ho999|
计算后
fmt = "%-10s" + ("|#{"%2s" % ln}%3d" * ints.size) + "|"
#=> %-10s|ho%3d|ho%3d|ho%3d|ho%3d|ho%3d|"
puts "%-30s%2s%3d%2s%3d%2s%3d%2s%3d%2s%3d" % [tn,ln,a,ln,b,ln,c,ln,d,ln,e]
这是 Ruby,但许多语言都使用这种格式。我忘记了如何以相同的格式输出多个变量,而无需在每种情况下重复格式。在这里,我想要 5 个整数的“%3d%2s”,每个整数由“|”
分隔你可以这样写。
def print_my_string(tn, ln, *ints)
fmt = "%-10s" + ("|#{"%2s" % ln}%3d" * ints.size) + "|"
puts fmt % [tn, *ints]
end
然后,例如,
print_my_string("hello", "ho", 2, 77, 453, 61, 999)
显示
hello |ho 2|ho 77|ho453|ho 61|ho999|
计算后
fmt = "%-10s" + ("|#{"%2s" % ln}%3d" * ints.size) + "|"
#=> %-10s|ho%3d|ho%3d|ho%3d|ho%3d|ho%3d|"