Skip to content

Commit 1e7ee6a

Browse files
[DOC] Improve format specification docs
One example to describe how `*` works actually prints a warning: ``` $ ruby -we "sprintf('%d', 20, 14)" => -e:1: warning: too many arguments for format string ``` I think it's better to not use examples that print warnings, so I propose to merge `*` docs with "width" specifier docs, and only include the "correct" example. After I believe `*` is not an actual flag, but a special value that the width specifier can take. Mention `*` special value in initial summary as well.
1 parent 6cd98c2 commit 1e7ee6a

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

doc/format_specifications.rdoc

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,9 @@ It consists of:
3030

3131
- A leading percent character.
3232
- Zero or more _flags_ (each is a character).
33-
- An optional _width_ _specifier_ (an integer).
34-
- An optional _precision_ _specifier_ (a period followed by a non-negative integer).
33+
- An optional _width_ _specifier_ (an integer, or <tt>*</tt>).
34+
- An optional _precision_ _specifier_ (a period followed by a non-negative
35+
integer, or <tt>*</tt>).
3536
- A _type_ _specifier_ (a character).
3637

3738
Except for the leading percent character,
@@ -125,13 +126,6 @@ Left-pad with zeros instead of spaces:
125126
sprintf('%6d', 100) # => " 100"
126127
sprintf('%06d', 100) # => "000100"
127128

128-
=== <tt>'*'</tt> Flag
129-
130-
Use the next argument as the field width:
131-
132-
sprintf('%d', 20, 14) # => "20"
133-
sprintf('%*d', 20, 14) # => " 14"
134-
135129
=== <tt>'n$'</tt> Flag
136130

137131
Format the (1-based) <tt>n</tt>th argument into this field:
@@ -152,6 +146,11 @@ of the formatted field:
152146
# Ignore if too small.
153147
sprintf('%1d', 100) # => "100"
154148

149+
If the width specifier is <tt>'*'</tt> instead of an integer, the actual minimum
150+
width is taken from the argument list:
151+
152+
sprintf('%*d', 20, 14) # => " 14"
153+
155154
== Precision Specifier
156155

157156
A precision specifier is a decimal point followed by zero or more
@@ -194,6 +193,11 @@ the number of characters to write:
194193
sprintf('%s', Time.now) # => "2022-05-04 11:59:16 -0400"
195194
sprintf('%.10s', Time.now) # => "2022-05-04"
196195

196+
If the precision specifier is <tt>'*'</tt> instead of a non-negative integer,
197+
the actual precision is taken from the argument list:
198+
199+
sprintf('%.*d', 20, 1) # => "00000000000000000001"
200+
197201
== Type Specifier Details and Examples
198202

199203
=== Specifiers +a+ and +A+

0 commit comments

Comments
 (0)