In Ruby, you can substitute arguments into a C-style format string using the String#%
method, like so:
'%.3d can be expressed in binary as %b' % [30, 30]
#=> "030 can be expressed in binary as 11110"
Kernel#sprintf
and Kernel#format
behave similarly:
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 also provides the ability to use named parameters within this format string:
'Hello, %{first_name} %{last_name}!' % {first_name: 'John', last_name: 'Doe'}
#=> "Hello, John Doe!"
But is there a way to use these features together? 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"
In other words, is there a way to use flags, width specifiers, precision specifiers, and types in format strings with named parameters? What's the form of %[flags][width][.precision]type
if I want to give the format sequence a name?
Try this:
'%<num>.3d can be expressed in binary as %<num>b' % {num: 30}
# => "030 can be expressed in binary as 11110"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With