Lets start by creating a simple array
an_array = [“osi”, 15, 31337]
Woah there fucko, different types in the same array ? (second nature to perl coders, still a novelty to me) Thats right kids, although the dreaded offset still applies;
puts an_array[1]
Produces the output “15”
an_array[1] = 25
reassigns a value in the array;
an_array[6] = “t00t”
“hold on, i thought the array was only 3 objects big ?” well now its 6 objects big, ruby arrays grow as needed, ah the joys.
puts an_array
reveals all, it fills in any unspecified values with ‘nil’
A crude script that shows the basics;
an_array = ["osi", 15, 31337]
puts an_array
an_array[1] = 25
puts an_array[1]
an_array[6] = "t00t"
puts an_array
an_array[4,0] = ["inserted", "strings"]
puts an_array
an_array[0]=%w(blah, blah, blah)
puts an_array
A few of the more useful methods you’d use to handle arrays;
an_array = [109, 15, 103, 153, 94]
puts an_array.min #or max
Returns the min/max value.
an_array = [109, 15, 103, 153, 94]
puts an_array.sort
an_array = [109, 15, 103, 153, 94]
an_array[12] = 5
puts an_array
puts an_array.compact
Deletes all elements with the value ‘nil’
an_array = [109, 15, 103, 153, 94, 94]
puts an_array.uniq
Returns only unique elements of an array.
an_array = %w(ab, bc, cd, de, ef,)
puts an_array.grep(/e/)
Just like grep in TEH LUNIX, here it returns de and ef. Hashes are just as simple;
days_of_the_week = {
“First” => “Monday”,
“Second” => “Tuesday”,
“Third” => “Wedensday”,
“Fourth” => “Thursday”,
“Fifth” => “Friday”,
“Sixth” => “Saturday”,
“Seventh” => “Sunday”
}
puts days_of_the_week.keys or puts days_of_the_week.values
Returns either the keys or values of a hash.
puts days_of_the_week.key?(“second”) #true
puts days_of_the_week.values?(“march”) #false
Checks if the specified term exists as a key or value.
puts days_of_the_week.key.to_a
Returns a copy of the hash in array form.
This article was originally written by pigsbig78 |