简体   繁体   中英

How can I convert all numbers in a string to hexadecimal using gsub?

I'm trying to convert all numbers in a string to hex. I tried this code:

str.gsub(/(\d+)/, '\1'.to_i.to_s(16))

But this replaces every number with 0 because it modifies the string '\\1' instead of the number that replaces \\1 .

How can I do this correctly using gsub ?

String#gsub accepts a block. The return value of the block is used as the replacement value:

>> str = '100 200'
=> "100 200"
>> str.gsub(/\d+/) { |x| x.to_i.to_s(16) }
=> "64 c8"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM