I have:
sprintf("%02X" % 13)
Which outputs:
=>"OD"
I want my output to be:
=>"%0D"
I've tried:
sprintf("\%%02X" % 13)
but I get an error warning: too many arguments for format string
. The same goes for:
sprintf("%%02X" % 13)
Is it possible to add a leading %
in sprintf alone?
A literal %
has to be escaped as %%
:
sprintf('%%') #=> "%"
Furthermore, you should either use sprintf
or %
, not both:
sprintf('%%%02X', 13) #=> "%0D"
# ^
# comma here
'%%%02X' % 13 #=> "%0D"
# ^
# percent sign here
If these are too many percent signs, you can separate the string literal to make it more obvious:
sprintf('%%' '%02X', 13)
#=> "%0D"
In Ruby, 'foo' 'bar'
is equivalent to 'foobar'
, i.e. adjacent string literals are automatically concatenated by the interpreter.
sprintf('%%%02X', 13)
# => "%0D"
From the ruby docs:
Field: % | Other Format: A percent sign itself will be displayed. No argument taken.
i.e. You must escape the %
character with a double %%
; much like you much escape a single \
with \\
in regular strings.
Another possibility is to use Integer#to_s
:
"%" + 13.to_s(16).rjust(2, '0').upcase
#=> "%0D"
And since %
has a higher precedence than +
, you could also write :
"%" + "%02X" % 13
#=> "%0D"
which is equivalent to
"%" + ("%02X" % 13)
#=> "%0D"
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