Introduction to Ruby

Everything you need to know to start programming in Ruby.

Sure enough, that returns 2.5. Unlike many other languages, Ruby requires a leading 0 for fractional numbers; you must say 0.5, rather than .5.

You can convert a string to an integer or float using the to_i and to_s methods:

"5".to_i
"5".to_f

All objects in Ruby have a similar to_s method, which turns the object into a string.

One datatype in Ruby that surprises some newcomers is the symbol. You can think of symbols as special kinds of strings that take up far less room in memory, especially when they are used in multiple locations. Symbols, which begin with a colon (for example, :reader) cannot always be used in place of strings, but they allow programmers to make programs more readable. They also are used on occasion to refer to objects and methods, as I explain later in this article.

Interpolation and Methods

Like many other high-level languages, Ruby lets us interpolate values inside of double-quoted strings. (Single-quoted strings are taken literally, as is the convention in many other languages.) For example:

name = "Reuven"
"Hello, #{name}"

The above expression is equivalent to:

Hello, Reuven

Within the #{ }, we can put any Ruby expression, not only a variable name:

name = "Reuven"
print "Hello, #{name}. Your name is #{name.length} letters long."
print "Backwards, your name is '#{name.reverse}'."
print "Capitalized, your backwards name is '#{name.reverse.capitalize}'."

As you can see, interpolation lets us put arbitrarily complex expressions within a double-quoted string. But wait a second—what are we doing with the expressions name.length, name.reverse and name.reverse.capitalize?

The answer is that strings, like everything in Ruby, are objects. Nearly anything we will do with a string is expressed as a method, rather than as a standalone function. If you want to reverse a string, get its length, capitalize it or break it apart, you will invoke a method on the object using Ruby's object.message syntax. For example:

name.reverse

The above code returns a new string object, whose value is the reverse of name. Name itself is not altered in the process. Because this new returned object is also a string, we can invoke any string method on it, including capitalize, as we saw before. Ruby programmers often end up chaining methods together to accomplish a task.

Methods invoked on an instance of an object are often referred to as Object#method in Ruby documentation. So, the above method would be referred to as String#reverse.

How do we know to which methods a particular object will respond? One way is to ask the object what class it is:

name.class

We also can ask an object whether it is a member of a particular class:

name.is_a?(String)

This might look a bit strange, both because of the question mark in the method name and the parameter that comes after it. But it works just like the other methods we have invoked so far. We send an is_a? message to name, which returns a Boolean (true or false) response. The argument to is_a? is a class name, which is String.

If we would prefer not to look up the API documentation for Ruby strings, we simply can ask the object itself what methods it will respond to:

name.methods

This returns an array (that is, a list) of methods to which name responds. We will look at arrays in a moment, but it's important to realize that name.methods is not a string; rather, it's an array whose contents happen to be strings. However, arrays respond to a built-in sort method, which returns a new array whose contents are ordered:

name.methods.sort

I probably invoke OBJECT.methods.sort at least once each day, rather than look through a book or on-line API for Ruby.

Arrays and Hashes

If you have worked with Perl or Python in the past, you won't be surprised to learn that Ruby has built-in arrays (as mentioned above) and hashes. We create an array with square brackets:

an_array = [1, "two", true]

An array can contain any number of objects, and each object can be of any type, including another array. The above array contains three objects (of types Fixnum, String and Boolean, respectively). Each item in an array has a unique index; the first element has an index of 0. We can retrieve items as follows:

an_array[1]

The above expression returns "TWO", the item with an index of 1 in an_array. Arrays are mutable, meaning that we can replace any of the items by assigning to that index:

an_array[1] = "TWO"

We can use a negative index to count from the back of the array; thus an_array[-1] returns the Boolean value true. We also can view a subset of the original array by passing two indexes separated by a comma, indicating the first and last index that we want:

an_array[0,1]

To combine all of the elements of an array into a string, we can use the join method, for example:

an_array.join(", ")

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Inspired by You

noman13bd's picture

Hi, i read this article and install and do some programming with RoR. Here is some of example what i do
Ruby On Rails installation on Windows
Ruby on Rails installation in Ubuntu
autocompleter example in RoR
live Validation for RoR

Ismail Muhammad Noman
share-facts.blogspot.com

I'm only just starting to

Anonymous's picture

I'm only just starting to learn Ruby, but this seems wrong:

"We also can view a subset of the original array by passing two indexes separated by a comma, indicating the first and last index that we want:

an_array[0,1]"

Shouldn't it be "indicating the first index and the LENGTH OF THE SUBSTRING that we want"?

Nice and fast intro (plus two typos)

Praxis's picture

Greetings.
I enjoyed this fast intro to Ruby, which quickly points out the basics with nice and clear examples for anyone with some programming experience to easily go hands-on.

I did notice these two typos:

1. When you mention string conversion methods, it is written "You can convert a string to an integer or float using the to_i and to_s methods", but I believe you meant "to_i and to_f"

2. When you give the "id_squared" method example, you mention in the explaining paragraph that it "returns its doubled value", where it should be the "squared value"

Regardless of this, I did enjoy reading this intro.

Congratulations.

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState