3

I have a string with non-printable characters.

What I am currently doing is replacing them with a tilde using:

string.gsub!(/^[:print:]]/, "~")

However, I would actually like to convert them to their integer value.

I tried this, but it always outputs 0

string.gsub!(/[^[:print:]]/, "#{$1.to_i}")

Thoughts?

falsetru
  • 357,413
  • 63
  • 732
  • 636
Dan Grahn
  • 9,044
  • 4
  • 37
  • 74

2 Answers2

7

String#gsub, String#gsub! accept optional block. The return value of the block is used for substitution.

"\x01Hello\x02".gsub(/[^[:print:]]/) { |x| x.ord }
# => "1Hello2"
falsetru
  • 357,413
  • 63
  • 732
  • 636
0

Object#inspect is also an option if you just need to output string with non-printable characters to log or for debug purposes.

puts "\x01Hello\x02".inspect
# => "\u0001Hello\u0002"
Mike
  • 2,468
  • 3
  • 25
  • 36