Named format string parameters with format specifiers

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] #=> "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 in 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? For example:.

 '%{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 is the form of %[flags][width][.precision]type if I want to specify a name formatting sequence?

+8
ruby
source share
1 answer

Try the following:

 '%<num>.3d can be expressed in binary as %<num>b' % {num: 30} # => "030 can be expressed in binary as 11110" 
+12
source share

All Articles