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'
Advertisements

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s