Converting Fixnum to String or ‘Character’ and back in Ruby

Took me a while to find out, so ill share ๐Ÿ™‚

# 1.8.7 / 1.8.6 only, not 1.9.x
'a'[0] == 97

# universal 1.8.x / 1.9.x
97.chr == 'a'
97 == ?a

# by mr woeber
'a'.unpack('C*').first == 97
[97].pack('C*') == 'a'

2 thoughts on “Converting Fixnum to String or ‘Character’ and back in Ruby

  1. The other day I was in need of converting between a String and its representation of ASCII-Codes, which was supposed to work in 1.8.x => 1.9.x.
    Odd, because ruby<1.8.7 doesn't have the String#bytes method (and it was a patch for a gem, so I didn't want to monkey-patch String).

    The following works from 1.8.? .. 1.9.? (took me also a while to find out, so ill share ๐Ÿ˜‰

    'ABC'.unpack('C*') == [65, 66, 67]
    [65, 66, 67].pack('C*') == 'ABC'

Leave a reply to pragmatig Cancel reply