本文介绍了Ruby将不可打印的字符转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有不可打印字符的字符串.

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.

我尝试过,但是它总是输出0

I tried this, but it always outputs 0

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

有想法吗?

推荐答案

String#gsub String#gsub!接受可选块.该块的返回值用于替换.

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"

这篇关于Ruby将不可打印的字符转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:24
查看更多