문제

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"

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top