26334 total geeks with 3498 solutions
Recent challengers:
 Welcome, you are an anonymous user! [register] [login] Get a yourname@osix.net email address 

Articles

GEEK

User's box
Username:
Password:

Forgot password?
New account

Shoutbox
MaxMouse
It's Friday... That's good enough for me!
CodeX
non stop lolz here but thats soon to end thanks to uni, surely the rest of the world is going good?
stabat
how things are going guys? Here... boring...
CodeX
I must be going wrong on the password lengths then, as long as it was done on ECB
MaxMouse
lol... the key is in hex (MD5: of the string "doit" without the "'s) and is in lower case. Maybe i should have submitted this as a challenge!

Donate
Donate and help us fund new challenges
Donate!
Due Date: Jun 30
June Goal: $40.00
Gross: $0.00
Net Balance: $0.00
Left to go: $40.00
Contributors


News Feeds
The Register
Quantum boffins and
bread-heads form
new VC fund
NASA serves up
Curiosity"s
billion-pixel
panorama
That
Microsoft-Nokia
merger you"ve been
predicting? It"s no
go
Microsoft caves on
Xbox One DRM and
used-game controls
Kim Dotcom victim
of "largest data
MASSACRE in
history"
Google preps wave
of machine learning
apps
Reg to
Australia: Here"s
your chance to find
NBN answers
Microsoft breaks
bug-bounty
virginity in
$100,000 contest
Google"s JavaScript
challenger gains
better tools,
performance
Google joins
Amazon, HP,
Rackspace in easing
HDD data importing
Slashdot
Amazon Vows To
Fight Government
Requests For Data
2 Men Accused of
Trying To Make
X-Ray Weapon
Monsanto Executive
Wins World Food
Prize
Microsoft Launches
$100k Bug Bounty
Program
The Plight of Star
Wars Droids
Java API and
Microsoft"s
.NET API: a
Comparison
MakerBot Merging
With Stratasys
Microsoft Kills
Xbox One Phone-Home
DRM
Billion-Pixel View
of Mars Snapped By
Curiosity
Deb Nicholson Talks
About the Open
Invention Network
(Video)
Article viewer

Arrays in Ruby



Written by:rae
Published by:SAJChurchey
Published on:2008-05-16 13:46:08
Topic:Ruby
Search OSI about Ruby.More articles by rae.
 viewed 11744 times send this article printer friendly

Digg this!
    Rate this article :
A brief introduction to arrays in Ruby.

An array is nothing more than a collection of values which can be accessed by the same variable name. This is helpful in storing large amounts of related data. The simplest way to understand the concept of an array is to think of a list of values. The name of the list is your array's variable name. A simple string declaration in Ruby would look like this:

myString = "This is my string"


However, an array containing some string elements would be declared like this,

myArray = ['This', 'is', 'my', 'code']


Since Ruby is an object-oriented language, abstract data types, like arrays, are actually classes. Methods related to arrays are defined in the Array class and is a part Ruby's core language. Hence, all distributions of Ruby will contain this class. An Array object is created using the new method. Below is an example of doing the same.

myArray = Array.new


Remember that if you've already declared the array values like in the first example, you do not need to create the array using the new method. The new method will create only an empty array with no values. Another way to create an array and initialize its values:

myArray = Array.[](1,2,3)


Individual values of an array are accessed by their indexes. An index is a numerical subscript which denotes the element number. For instance, in our last example - the element '1' will have an index of 0. The element '2' will have an index of 1 and so on. Notice that the index values start from 0 and not 1 as is the case with quite a few other languages. Thus, to access the element of an array and do an operation on it, we need to simply provide its index. The code shown below creates a new array and prints out the second element using the puts method.

likeWords = ["first", "second", "third"]
puts likeWords[1]


One of the most common operations that are used on arrays is inserting and removing data. When we want to add data at the end of the array, we use the push method, and when we want to remove the last element of the array we use the pop method. Ruby allows us to treat the array like a stack, a data structure where insertions and deletions can only be done at one end of the array. Have a look at the code below to understand how these two methods are used:

# Array Declaration
likeWords = ["first", "second", "third"]

puts likeWords.length
puts likeWords[3]

# Adding an element
likeWords.push "fourth"

puts likeWords.length
puts likeWords[3]

# Removing the last element
likeWords.pop

puts likeWords.length
puts likeWords[3]


Output
-------
3
nil
4
fourth
3
nil



In the above example, the length of the array when created is 3, then becomes 4 after pushing another element, and then becomes 3 again after we pop the element we just pushed. Notice that when we try to access the fourth element of the array (the 3rd index), the resultant output is 'nil'. If you want to find the number of elements an array holds, you can use the length or size method. The latter is just an alias of the length method and will give you the exact same output. The code below prints out the number of elements an array called 'likeWords' contains.

puts likeWords.length


On similar lines, the last method simply gives you access to the last element of the array without deleting or changing it in any way. The syntax for printing out the last element of an array is given below.

puts likeWords.last


This wraps up our discussion of Ruby arrays. There are many more methods that are defined for the Array class but this should suffice as an introduction. For further reference, The Ruby Way by Hal Fulton is a nice book though not intended for novices. If you're just starting out with Ruby, Learn to Program by Chris Pine is an excellent introduction

Written by Rae

Did you like this article? There are hundreds more.

Comments:
thinkt4nk
2008-05-16 18:48:34
any shift/unshift methods? is 'nil' synonymous with undef? can one interpolate variable names in indexes? i.e. someArray[someVariable] = someValue;
rae
2008-05-16 22:40:25
Yes, the Array class does have shift/unshift methods. The shift simply removes the first element of the array just like pop does it for the last.

Nil in Ruby is actually an object and signifies 'empty'. You can say it is the Ruby equivalent to Perl's undef but its different in the sense that its not a undefined variable value. Its an object in its own right.

And yes, using a var as an index of a array is perfectly valid in Ruby. (If I understood you correctly)
Anonymous
2009-08-11 11:36:30
I was trying to make the array but i feel some problems in creating what method i want to use for this now i will try again as i get some time form offering services of email hosting services along with the services of ftp hosting services which you can use at affordable price now i am going to introduced audio hosting services which are more reliable to use, but i like the stuff on your pages and will return to see you again what you are making new things.
Anonymously add a comment: (or register here)
(registration is really fast and we send you no spam)
BB Code is enabled.
Captcha Number:


Blogs: (People who have posted blogs on this subject..)
reacher
The Ruby Way on Wed 27th Aug 6pm
I've recently come back to OSIX and taken all the challenges again. This next time around, however, I'm using Ruby to tackle them. I will admit that my old C versions of some solutions ran faster (especially the brute force ones), but coding the Ruby ve
bb
Ruby on Rails on Tue 10th Oct 9am
I installed ruby and wrote my first ruby on rails web application. It was quite an enjoyable experience. Certainly more fun than asp.net (which is bloody unproductive) I suggested we knock some internal application up in it for my company to have ap


     
Your Ad Here
 
Copyright Open Source Institute, 2006