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?

undur_gongor
  • 15,657
  • 5
  • 63
  • 75

2 Answers2

64

You can use Array#pack:

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

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

Stefan
  • 109,145
  • 14
  • 143
  • 218
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"
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100