Introduction to Ruby

Everything you need to know to start programming in Ruby.

The above code creates a single string, whose contents are the values from an_array, with “, ” between each pair of elements.

Hashes are similar to arrays, except that instead of storing values using an ordered, numeric index, they are stored with keys, for example:

my_hash = {'a' => 1, 'b' => 2}

We can now retrieve either of the two values, by using its key:

my_hash['a']
my_hash['b']

The above lines of code return the numbers 1 and 2, respectively. As with arrays, we can store any object as a value in a hash; it doesn't have to be an integer.

We can retrieve the keys and values of a hash with the Hash#keys and Hash#values methods, respectively. (Later, I explain how to iterate over the keys and values to retrieve contents from a hash.) Sometimes, however, we simply want to know if a particular key exists in a hash. This is easily accomplished with Hash#has_key?, which takes a string as a parameter and returns a Boolean value. The following code thus would return true:

my_hash.has_key?("a")

Conditionals

Every language lets us execute code conditionally. In Ruby, this normally is done with an if statement. Consider the following (somewhat contrived) example:

if server_status == 0
print "Server is in single-user mode"
elsif server_status == 1
print "Server is being fixed "
elsif network_response == 3
print "Server is available"
else
print "Network response was unexpected value '#{network_response}'"
end

Notice that Ruby does not require parentheses around the condition. And although the condition does not have to return a Boolean value, Ruby will produce a warning if you try to use = (that is, assignment) in the condition, rather than == (that is, comparison). The == comparison operator works on all objects; there are no separate text comparison and numeric comparison operators as in Perl. This is true for < and > also, which can be used to compare strings as well as numbers. Finally, Ruby does not use opening or closing braces; instead, it closes the conditionally executed block of code with end.

As with Perl, you can use if and unless as suffixes to make a statement conditional:


print "We won!" if our_score > their_score
print "Here is your change of #{amount_paid - price}!"
    unless amount_paid <= price

You also can do things like:


if inputs.length < 4
    print "Not enough inputs!\n"
end

And, also:

if not my_hash.has_key?("debug")
    print "Debugging is inactive.\n"
end

Loops

Ruby does have some looping operators, such as for and while. But the real fun and excitement is in doing things such as this:

5.times {print "hello\n"}

Think about it—we're invoking a method on a number, using the standard Ruby method-invocation syntax. The times method for integers executes a block of code a particular number of times. So, the above line of code executes five times, printing the word hello (followed by a new line) each time.

Blocks can take parameters as well, between pipe (|) characters:

5.times {|iteration| print "Hello, iteration number #{iteration}.\n"}

We similarly can iterate over the elements of an array with the each method:

an_array = ['Reuven', 'Shira', 'Atara', 'Shikma', 'Amotz']
an_array.each {|name| print "#{name}\n"}

A variation of the each method, called each_with_index, requires a block that takes two parameters. The first parameter is the item, and the second is the index:

an_array = ['Reuven', 'Shira', 'Atara', 'Shikma', 'Amotz']
an_array.each_with_index {|name, index| print "#{index}: #{name}\n"}

At a certain point, blocks become difficult to read in this syntax. Ruby provides an alternate syntax, replacing the curly braces with do and end:

an_array = ['Reuven', 'Shira', 'Atara', 'Shikma', 'Amotz']
an_array.each_with_index do |name, index|
    print "#{index}: #{name}\n"
end

We can iterate over a hash in several ways. One way is to use the type of iteration that Perl and Python programmers have used for years, getting the hash's keys (via Hash#keys, which returns an array) and then grabbing the value that goes with the key:

state_codes = {'Illinois' => 'IL', 'New York' => 'NY',
               'New Jersey' => 'NJ', 'Massachusetts' => 'MA',
               'California' => 'CA'}

state_codes.keys.each do |state|
    print "State code for #{state} is #{state_codes[state]}.\n"
end

Of course, we might want to sort the keys before iterating over them:

state_codes.keys.sort.each do |state|
    print "State code for #{state} is #{state_codes[state]}.\n"
end

Ruby provides an easier way to perform this task, the each_pair method:

state_codes.each_pair do |state, code|
    print "State code for #{state} is #{code}.\n"
end

______________________

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.

Free Dummies Books
Continuous Engineering

Learn:

  • What continuous engineering is
  • How to continuously improve complex product designs
  • How to anticipate and respond to markets and clients
  • How to get the most out of your engineering resources

Get your free book now

Sponsored by IBM

Free Dummies Books
Service Virtualization

Learn to:

  • Define service virtualization
  • Select the most beneficial services to virtualize
  • Improve your traditional approach to testing
  • Deliver higher-quality software faster

Get your free book now

Sponsored by IBM