Ruby Quirks: String#[]

In the series of posts that have Ruby Quirks in the title, my goal is to keep track of unexpected behaviors I encounter with Ruby as I continue learning the language. I will divide the quirks into separate sections (most likely respective classes) as I encounter them. Since it is the same post, that will be constantly updated, I will put the date I encountered a particular quirk next to it’s subheading. I am going to take Pete’s advice and write separate posts for each quirk I encounter.

Quirk Information

Class: String

Operator: []

String class has [] operator that allows us to get a substring for a given string. For example:

name = "Ashish"
str = name[2,3] # str contains "his"

However, if you pass a single index to the [] operator, the response is not something you would expect. For example:

char = name[1] # char contains 115, the ASCII representation of the character s

While we are in the topic of characters & their ASCII representation, Ruby provides a ? operator to evaluate the ASCII representation of a string. For example:

?a # returns 97
?A # returns 65
?s # returns 115
?AA # results in SyntaxError

This quirk can be seen in Ruby 1.8.7 & earlier versions of Ruby. However, from 1.9.1, the behavior is as expected. For example, in 1.9.1 and beyond:

?a # returns a
"Ashish"[1] # returns s


4 thoughts on “Ruby Quirks: String#[]

  1. String#[] also allows you to pass a regexp as the first argument, and an integer index of matches as the second. This is very handy if you want to use a regexp to get a substring of a string.

    I did something similar to this the other day at work:

    >> url = “”
    => “”
    >> url[ /https?:\/\/([^\/]+)/, 1 ]
    => “”

    String#[] is aliased as String#slice, and there are a few other tricks waiting in the docs for you.

  2. Also, I would recommend writing new posts for new ruby quirks, so that anyone following your rss feed can be updated about the change. I’d certainly like it better. 😉

    • Yeah. I was not thinking clearly initially. I think if I tag them all Ruby Quirks, I can have them all listed in one page while them being separate posts. I will change that. Thanks for the advice & thanks for reading!

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.