Paul
Paul

Reputation: 119

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?

Upvotes: 2

Views: 156

Answers (1)

falsetru
falsetru

Reputation: 369334

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"

Upvotes: 7

Related Questions