Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named format string parameters with format specifiers

Tags:

ruby

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?

like image 936
Ajedi32 Avatar asked May 28 '14 19:05

Ajedi32


1 Answers

Try this:

'%<num>.3d can be expressed in binary as %<num>b' % {num: 30}
# => "030 can be expressed in binary as 11110"
like image 141
Uri Agassi Avatar answered Nov 13 '22 10:11

Uri Agassi