diff options
| author | David RodrÃguez <2887858+deivid-rodriguez@users.noreply.github.com> | 2025-09-07 17:41:59 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-09-08 00:41:59 +0900 |
| commit | 1e7ee6a4ba3ee626d9fb99be4a35365bce74b0f9 (patch) | |
| tree | f74692a5971f36230e65112a18deaa60d835dd3e | |
| parent | 6cd98c24fe9aeea3829ac3d554a277f053cec0be (diff) | |
[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.
| -rw-r--r-- | doc/format_specifications.rdoc | 22 |
1 files changed, 13 insertions, 9 deletions
diff --git a/doc/format_specifications.rdoc b/doc/format_specifications.rdoc index bdfdc24953..a2755256df 100644 --- a/doc/format_specifications.rdoc +++ b/doc/format_specifications.rdoc @@ -30,8 +30,9 @@ It consists of: - A leading percent character. - Zero or more _flags_ (each is a character). -- An optional _width_ _specifier_ (an integer). -- An optional _precision_ _specifier_ (a period followed by a non-negative integer). +- An optional _width_ _specifier_ (an integer, or <tt>*</tt>). +- An optional _precision_ _specifier_ (a period followed by a non-negative + integer, or <tt>*</tt>). - A _type_ _specifier_ (a character). Except for the leading percent character, @@ -125,13 +126,6 @@ Left-pad with zeros instead of spaces: sprintf('%6d', 100) # => " 100" sprintf('%06d', 100) # => "000100" -=== <tt>'*'</tt> Flag - -Use the next argument as the field width: - - sprintf('%d', 20, 14) # => "20" - sprintf('%*d', 20, 14) # => " 14" - === <tt>'n$'</tt> Flag Format the (1-based) <tt>n</tt>th argument into this field: @@ -152,6 +146,11 @@ of the formatted field: # Ignore if too small. sprintf('%1d', 100) # => "100" +If the width specifier is <tt>'*'</tt> instead of an integer, the actual minimum +width is taken from the argument list: + + sprintf('%*d', 20, 14) # => " 14" + == Precision Specifier A precision specifier is a decimal point followed by zero or more @@ -194,6 +193,11 @@ the number of characters to write: sprintf('%s', Time.now) # => "2022-05-04 11:59:16 -0400" sprintf('%.10s', Time.now) # => "2022-05-04" +If the precision specifier is <tt>'*'</tt> instead of a non-negative integer, +the actual precision is taken from the argument list: + + sprintf('%.*d', 20, 1) # => "00000000000000000001" + == Type Specifier Details and Examples === Specifiers +a+ and +A+ |
