Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How do you include a % sign in sprintf output?

Tags:

ruby

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?

like image 276
user3574603 Avatar asked Jun 16 '17 09:06

user3574603


3 Answers

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.

like image 88
Stefan Avatar answered Nov 15 '22 07:11

Stefan


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.

like image 34
Tom Lord Avatar answered Nov 15 '22 07:11

Tom Lord


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"
like image 38
Eric Duminil Avatar answered Nov 15 '22 07:11

Eric Duminil