tundal45@wordpress:~$

>puts "Hello, World!"

Posts Tagged ‘[ ] operator

Ruby Quirks: String#[]

with 4 comments

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

Written by tundal45

July 10, 2010 at 2:12 am

Posted in ruby

Tagged with , , ,