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


i'm trying convert numbers in string hex. tried code:

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

but replaces every number 0 because modifies string '\1' instead of number replaces \1.

how can correctly using gsub?

string#gsub accepts block. return value of block used replacement value:

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

Comments