在Ruby中,您可以使用String#%
方法将参数替换为C样式的格式字符串,如下所示:
'%.3d can be expressed in binary as %b' % [30, 30]
#=> "030 can be expressed in binary as 11110"
Kernel#sprintf
和Kernel#format
表现相似:
sprintf('%.3d can be expressed in binary as %b', 30, 30)
#=> "030 can be expressed in binary as 11110"
format('%.3d can be expressed in binary as %b', 30, 30)
#=> "030 can be expressed in binary as 11110"
Ruby还提供了在此格式字符串中使用命名参数的功能:
'Hello, %{first_name} %{last_name}!' % {first_name: 'John', last_name: 'Doe'}
#=> "Hello, John Doe!"
但是有没有办法一起使用这些功能? E.g:
'%{num}.3d can be expressed in binary as %{num}b' % {num: 30}
# I want: "030 can be expressed in binary as 11110"
# Actual: "30.3d can be expressed in binary as 30b"
换句话说,有没有办法在带有命名参数的格式字符串中使用flags,width说明符,精度说明符和类型?如果我想给格式序列命名,那么%[flags][width][.precision]type
的形式是什么?
答案 0 :(得分:14)
试试这个:
'%<num>.3d can be expressed in binary as %<num>b' % {num: 30}
# => "030 can be expressed in binary as 11110"