In Ruby, you can replace arguments with a C-style format string using the String#% method, for example:
'%.3d can be expressed in binary as %b' % [30, 30]
Kernel#sprintf and Kernel#format behave similarly:
sprintf('%.3d can be expressed in binary as %b', 30, 30)
Ruby also provides the ability to use named parameters in this format string:
'Hello, %{first_name} %{last_name}!' % {first_name: 'John', last_name: 'Doe'}
But is there a way to use these features together? For example:.
'%{num}.3d can be expressed in binary as %{num}b' % {num: 30}
In other words, is there a way to use flags, width specifiers, precision specifiers, and types in format strings with named parameters? What is the form of %[flags][width][.precision]type if I want to specify a name formatting sequence?
ruby
Ajedi32
source share