Given an integer - say, x=20
, I'd like to convert this into a string containing its escaped octal character. I.e. ...
x=20
# y = ... Some magic
p y # => "\024"
The closest I've managed to get is by using:
x.to_s(8) # => "24"
However, I'm completely stumpted on how to convert this string into an escaped octal character! Any ideas, internet?
Just use Kernel#sprintf
to format the number.
Like this
x = 20
y = sprintf('\%03o', x)
puts y
output
\024
Update
Maybe I misunderstood you. If you just want a character with the given code point then just use Integer#chr
.
Like this
x = 20
y = x.chr
p y
output
"\x14"