How Letters and Words Differ from Numbers in Ruby

By Christopher Haupt

Programming languages, like Ruby, keep track of the different kinds of data that you may want to work with in a program. For each type of data, the language will often provide common and unique capabilities for manipulating that data.

In Ruby, numbers are a type of data. You can do a variety of things with numbers, including performing the common arithmetic operations on them.

Letters, also known as characters, are another type of data in Ruby. Ruby can work with individual characters or collections of characters (like words or sentences). Ruby, like many other programming languages, calls these collections strings.

Characters, and strings that contain characters, can represent more than the standard alphabet (A to Z). Characters can be any of the visible symbols on your keyboard, and many that aren’t directly visible (including things like spaces, tabs, and other special symbols).

This can get confusing, because that means that the character “3” and the number 3 look exactly the same. How does Ruby tell them apart?

Notice the quotation marks in that last paragraph. Ruby remembers that you used quotation marks when it repeats its results:

2.2.2 :004 > "3"
=> "3"
2.2.2 :005 > 3
=> 3

In Ruby, if you want to refer to a string of characters, no matter what they are, you put them between quotation marks. If you mean an actual number, you just write the digits of that number without quotation marks. Try this:

2.2.2 :001 > "hello"
=> "hello"
2.2.2 :002 > "1000"
=> "1000"
2.2.2 :003 > 1000
=> 1000

The first item, “hello”, is a regular English word and is a string. The second item, “1000”, is a string representing one thousand. And the third item, 1000, is an actual number.

Behind the scenes, Ruby tracks the differences between these resulting objects and enables different kinds of powerful features depending on the type of that data.

In your programs, you use straight quotes (” “), and if you’re using IRB or a programming editor like Atom, you should be okay. If you get an error when using strings, you may be using typographic quotes, also known as curly quotes. This may be because you used a word processor (like Microsoft Word) to write code instead, and Ruby may get confused.