Ruby Arrays
Friday, March 9th, 2007We 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 “
a.clear -> [ ] #an empty array
To find out the length of the array use “
a.length -> [a,b,c ] #length array
To remove the last element in the array use the “
a = [ "a", "m", "z" ]
a.pop -> “z”
a -> ["a", "m"]
To add an element(s) into the array use the “
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 “
a = [ "a", "b", "c" ]
a.each {|x| print x, ” - ” }
produces:
a - b - c -
To loop through an array using the index use the “
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 “
arr.empty? -> true or false
To join the elements of an array into a string use the “
[ "a", "b", "c" ].join -> “abc”
[ "a", "b", "c" ].join(”-”) -> “a-b-c”
To concatenate array you can use the “
[ "a", "b" ].concat( ["c", "d"] ) -> ["a", "b", "c", "d"]
To remove the nil elements in the array use the “
[ "a", nil, "b", nil, "c", nil ].compact -> ["a", "b", "c"]