Ruby convert non-printable characters into numbers

Deadly 提交于 2019-12-10 17:45:11

问题


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?


回答1:


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"



回答2:


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"


来源:https://stackoverflow.com/questions/20146704/ruby-convert-non-printable-characters-into-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!