A Little Ruby Primer

Here is a cheat sheet to help you (and me!) remember the fundamentals of Ruby.

Strings and Integers

Ruby has two powerful classes called String and Fixnum with lots of built-in power.

Arrays

Arrays are ordered sets of data that can be manipulated in a variety of helpful ways.

  • Elements in an array are given index numbers which correspond to their order. Index numbering starts at 0, so the first element of my_array would be accessed like so: my_array[0].
  • There are a huge number of helpful methods you can call on arrays. These include .length, .reverse, and .sort. The full documentation can be found here.
  • Looping through an array is easy with the .each method. This method takes a code block which it will apply to each element in the array.
  • The power of arrays is extended even further with the Enumerable Module mixed in. Enumberable provides a comprehensive toolkit for manipulating and iterating over arrays. Documentation can be found here.
  • Arrays can be one-dimensional or multi-dimensional. An array that contains arrays is called a nested array. You can access the elements inside the inner array by using stacked indices. my_array[2][0] would return the first element inside the third array inside my_array.
  • Arrays have destructive methods that end with a bang: !. These methods (like sort!) will permanently alter the original array object. The non-destructive versions will leave the original object as it was and create a new object that has been manipulated by the given code block.
  • Hashes

    Hashes are data sets organized by key/pair values.

  • Any object can be used as a hash key, but the most common keys are strings and symbols.
  • Like arrays, hashes have a number of powerful methods that let the user manipulate and explore them. Methods like has_key?, .length, and .any permit a user to peer inside the hash. Full documentation is found here.
  • Also like Arrays, Hashes include the Enumerable Module, which give users a great deal of power to iterate over and manipulate their hashes.
  • Hashes values are accessed using the key. For example, my_hash[key] would output the value associated with that key.
  • Adding a new value to a hash is as simple as using the hash name, with the key name in brackets, and setting it equal to the value. For example: my_hash[:key] = new_value.
  • Hashes can be looped through using the .each method, which takes both key and value as arguments and applies a given code block to each pair.