Skip to content

Data Structure Essentials

Bella Woo edited this page May 19, 2015 · 4 revisions

Hashes

h = hash.new Creates a new empty hash

h = { }

h[key] To look up a key

h[key] = value to set up a new key

.each

Arrays

a = Array.new Creates a new empty array

a = [ ]

a[5] To look up an element of in the array

a[5] = thing To set up a new thing to replace the element in the array

.each For each

.first The first item in the array

.push Append - Pushes the object to the end of the array. Returns the array itself, so several appends can be chained together.

.pop Removes the last item from self and returns it, or returns nil if the array is empty. Opposite of push

.shift Removes the first element from self and returns it, shifting all other elements down by one. Opposite of unshift.

.unshiftAdds objects to the front of self, moving other elements upwards. Opposite of shift.

.join

Strings

.split

.chars

.downcase

.upcase

.titlecase

gsub Replaces all occurrences of the item. Short for global sub. "banana".gsub("a", "x") ==> 'bxnxnx"

sub Replaces the first occurrence of the item "banana".sub("a", "x") ==> "bxnana"