Introduction to 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")
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
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
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- RSS Feeds
- Dynamic DNS—an Object Lesson in Problem Solving
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Designing Electronics with Linux
- Using Salt Stack and Vagrant for Drupal Development
- New Products
- A Topic for Discussion - Open Source Feature-Richness?
- Drupal Is a Framework: Why Everyone Needs to Understand This
- Validate an E-Mail Address with PHP, the Right Way
- What's the tweeting protocol?
- Kernel Problem
8 hours 31 min ago - BASH script to log IPs on public web server
12 hours 58 min ago - DynDNS
16 hours 33 min ago - Reply to comment | Linux Journal
17 hours 6 min ago - All the articles you talked
19 hours 29 min ago - All the articles you talked
19 hours 33 min ago - All the articles you talked
19 hours 34 min ago - myip
23 hours 59 min ago - Keeping track of IP address
1 day 1 hour ago - Roll your own dynamic dns
1 day 7 hours ago
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?




Comments
Inspired by You
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
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)
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.