Cheat Sheet

Ruby For Kids For Dummies Cheat Sheet

From Ruby For Kids For Dummies

By Christopher Haupt

One of the great advantages of learning to program with Ruby is the breadth of built-in and community-provided software. Being able to easily work with numbers and strings forms a foundation on which most programs are written. Leveraging built-in container classes such as Array and Hash makes it easy to work with a large and more complicated set of data. Finally, Ruby is extremely flexible, and there are very few things it can’t do, but one gotcha is to not accidentally name variables, classes, or methods using a Ruby built-in statement name or reserved word.

Ruby Basics, Numbers, and Strings

To get started with Ruby, you really only need to install Ruby itself and use a free code editor (not a word processor!). Notepad++, Atom, TextWrangler, and others are all good code editor choices. You’ll also commonly use a terminal or console program (free with all the common operating systems).

Once Ruby is installed, there are two common ways to run Ruby programs. If you type your Ruby code in a text file and save it, you run your code from a terminal with:

$ ruby my_code.rb

If you want to test small snippets of code, use IRB (Interactive Ruby) and start typing Ruby after the prompt:

$ irb
2.1.2 :001 > 

When testing out new code, you can easily print out the results of a calculation or string manipulation with the puts method:

2.1.2 :004 > puts 2.5 * 3
7.5
 => nil

Ruby provides a large number of built-in numeric and string methods.

Common numeric methods

Method Name Purpose
+, -, *, / Basic arithmetic
**2 Exponent (for example, raise to the second power)
( ) Use parentheses to adjust your math operation precedence
even? Returns true if even
odd? Returns true if odd
round Rounds to the nearest integer
upto, downto Loops up or down from number to another number

Common string methods

Method Name(s) Purpose
+, * Adds two strings together, repeat the string
length How long the string is
strip Removes leading and trailing white space
to_i Changes a string into a number
upcase,downcase Changes the case of the string
each_char Loops through the string returning each character
include? Returns true if a string is in another string
[] Returns character or substring
gsub Substitutes a new string where a pattern is found

You can use string interpolation to build up more complicated strings from content in other variables. Inside of double quotes, use the #{ } symbol to swap in the value of the enclosed variable:

2.1.2 :006 > age = "100"
 => "100"
2.1.2 :007 > name = "Rubyist"
 => "Rubyist"
2.1.2 :008 > "Hello #{name}, congrats on #{age} years!"
 => "Hello Rubyist, congrats on 100 years!"

Using Array and Hash Built-in and Related Methods

Ruby has many built-in classes, but perhaps the most useful objects used for holding other data are the container classes Array and Hash. You can save a lot of time coding if you remember that each of these classes has many useful methods for accessing and manipulating their contents.

Array basics

Use arrays for lists of information that you want to keep in order. Create a new empty array with empty square brackets [] and an array with contents by placing them between the square brackets, separated by commas:

empty_array = []
my_array = ["red", "green", "blue"]

Access items in an array using the index (position) of the item, starting with the first position whose number is zero (0):

2.1.2 :009 > my_array = ["red", "green", "blue"]
 => ["red", "green", "blue"]
2.1.2 :010 > puts my_array[0]
red
Method Name Purpose
my_array[1] Accesses the array in my_array at
index 1
length Returns the length of the array
<<, push Adds an object at the end of the array
pop Removes an object at the end of the array
insert Adds an object at the start of the array
shift Removes an object at the start of the array
sort Sorts the array
shuffle Randomizes positions of objects in the array
sample Picks a random object from the array
each Loops over the array, returning each element
join Combines each element into a string

Hash basics

Use hashes when you have information that you want to be able to look up by name (like a contact book), and order is not necessarily important. Create a new hash with empty curly brackets {} and a new hash with contents by providing a key and value separated by “hash rockets” (=>), and each key/value pair separated by commas:

2.1.2 :018 > empty_hash = {}
 => {}
2.1.2 :019 > contact_hash = {"mom" => 1234, "dad" => 4567}
 => {"mom"=>1234, "dad"=>4567}
Method Name Purpose
contact_hash[“mom”] Accesses the hash in the contact_hash
variable using key “mom” and returns its
value
contact_hash[“sis”] =
7878
Adds new value to the hash stored in the contact_hash variable using key sis
length Returns how many key/value pairs are stored in the hash
include? Checks if a key exists in the hash
keys Returns an array of all the keys in the hash
values Returns an array of all the values in the hash
empty? Returns true if the hash is empty
each Loops over each key/value pair in the hash, returning each
pair
merge Combines two hashes into one hash, possibly overwriting the
first hash’s keys with the second hash’s keys

Ruby’s Reserved Words

Ruby has a small set of words that are considered “reserved” and shouldn’t be used when naming variables or methods. The following table contains a list of Ruby reserved words that should not be used.

alias and BEGIN
begin break case
class def defined?
do else elsif
END end ensure
false for if
module next nil
not or redo
rescue retry return
self super then
true undef unles
until when while
yield _ _FILE_ _ _ _LINE_ _

In addition, you should check the standard Ruby documentation when naming your own classes and modules. If you use a name that is identical to an existing class (for example, String), you won’t create a new class, but rather change the existing one! This can have unexpected effects if you aren’t doing it on purpose.