Question

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?

Was it helpful?

Solution

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"

OTHER TIPS

You could use Array#pack:

[20].pack("C")  #=> "\x14"
x = 20

y = '\%03o' % x

puts y

If you use p to display y you would see 2 backslashes as p outputs ruby parsable strings.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top