Archive for the ‘ruby’ Category

Ruby Arrays

Friday, March 9th, 2007

We all know arrays are indexed collections. We also know that keys in array are integers and that the indices start at zero. So lets jump into some examples:

a= ['The','Dark','Side','Of'.'The','Moon']

a painful way to create the array :(
.another way


a = Array.new
a << "The"
a << "Dark"
a << "Side"
a << "Of"
a << "The"
a << "Moon"

same can be achieved by


a = %w{ The Dark Side Of The Moon}

much easier eh.. :)
that can also be achieved by


a = "The Dark Side Of The Moon".split(" ")

awesome :) :)

Here is a list of some useful array functions:

To remove all elements from an array use the “clear” method.


a.clear     ->     [ ]     #an empty array

To find out the length of the array use “length” method. Returns an integer


a.length     ->     [a,b,c ]     #length array

To remove the last element in the array use the “pop” method. Returns an object or nil


a = [ "a", "m", "z" ]
a.pop -> “z”
a -> ["a", "m"]

To add an element(s) into the array use the “push” method.


a = [ "a", "b", "c" ]
a.push(”d”, “e”, “f”) -> ["a", "b", "c", "d", "e", "f"]

As with any collection in ruby, you can use the “each” method to loop through its contents. It call the block once for each element. The element will be passed as a parameter.


a = [ "a", "b", "c" ]
a.each {|x| print x, ” - ” }
produces:
a - b - c -

To loop through an array using the index use the “each_index” method.
eachindex arr.eachindex {| anIndex | block } -> arr


a = [ "a", "b", "c" ]
a.each_index {|x| print x, ” - ” }
produces:
0 - 1 - 2 -

To find out if the array is empty or not use the “empty?” method. This method returns either true or false


arr.empty? -> true or false

To join the elements of an array into a string use the “join” method. An optional string separater is present as a parameter.


[ "a", "b", "c" ].join -> “abc”
[ "a", "b", "c" ].join(”-”) -> “a-b-c”

To concatenate array you can use the “concat” method.


[ "a", "b" ].concat( ["c", "d"] ) -> ["a", "b", "c", "d"]

To remove the nil elements in the array use the “compact” method.


[ "a", nil, "b", nil, "c", nil ].compact -> ["a", "b", "c"]