32

I have a string containing hex code values of ASCII characters, e.g. "666f6f626172". I want to convert it to the corresponding string ("foobar").

This is working but ugly:

"666f6f626172".scan(/../).map(&:hex).map(&:chr).join # => "foobar"

Is there a better (more concise) way? Could unpack be helpful somehow?

2
  • 7
    Like ["666f6f626172"].pack('H*')?
    – Stefan
    Apr 9, 2014 at 9:18
  • 1
    @Stefan. Yes, like that. Could you please post this as an answer? Apr 9, 2014 at 9:23

2 Answers 2

65

You can use Array#pack:

["666f6f626172"].pack('H*')
#=> "foobar"

H is the directive for a hex string (high nibble first).

1
  • 34
    pack/unpack will remain a mystery to me forever. Apr 9, 2014 at 10:13
23

Stefan has nailed it, but here's an alternative you may want to tuck away for another time and place:

"666f6f626172".gsub(/../) { |pair| pair.hex.chr } # => "foobar"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.