Ruby BASICS Cheat Sheet


Information Types:

Ruby has a few different types of information types; below are some examples of what defines each and how they're properly formatted.

Strings: Anything within quotes are considered strings.
Numbers: More commonly referred to as integers, are simply written as digits.
Booleans: Something that results in either a true or false condition.
Arrays: 'Lists' of items in which each item within the brackets are elements which coorespond to specific positions beginning with '0'.
Hashes: Detailed lists in which each key, (characters in quotes) point to a specific value, (key/value pairs).

"Hello World!"
12345
true/false
groceries = ["Milk", "Eggs", "Cheese", "Bread"]
menu = {"Pizza" => 3.50, "Pasta" => 5.50, "Soda" => 0.99}

Methods/Operators:

In Ruby, everything is an object, in order for objects to talk to one another there are what are called 'Methods'. Methods provide action to have performed on an object to actually 'do' something in code.

In Ruby, there are two central types of operators: Arithmetic and Comparison Operators. Arithmetic operators allow mathematical equations to be performed, whereas comparison operators allow the ability to compare between two objects.

String Methods: .reverse, .capitalize, .upcase, .downcase, .swapcase
Number Methods: .between?, .next, .odd?, .even?
Array Methods: .delete, .count, .join
Hash Methods: .compare, .flatten

Number Operators: +, -, *, /, **, %
Comparison Operators: ==, ===, !=, ||, &&, !, ?, :, <, >, <=, >=

General Ruby Syntax:

In Ruby, the general format of creating working code is as follows below:

def year(current)
  puts "It's #{current}!"
end
year(2015)

>> It's 2015!

def = states we're defining a method variable called 'year'.
year = a variable created to represent the name of the method.
(current) = considered a 'Parameter' that the user can pass in a value by calling it, (as we will in the last line).
puts = allows the string "It's 2015!" to be displayed on the user-console.
end = closes the defined method tag.
year(2015) = 'passes in' the variable 2015 into 'current', which then is interpolated within the #{} syntax of the puts line to output the next line.

Displaying to Console:

In Ruby, there are a few ways to display content to the user after a program runs.

puts = DOESN'T return the value of the method/variable, DOES print to console, & DOES automatically return a new line after the return statement.

print = puts = DOES return the value of the method/variable, DOES print to console, & DOES automatically return a new line after the return statement.

p = DOESN'T return the value of the method/variable. DOES print to console, & DOESN'T automatically return a new line after the return statement.

Below are some examples of how they differ:

puts "Kunal"
>>Kunal
>>nil

print "Kunal"
>>Kunalnil

p "Kunal"
>>"Kunal"
>>"Kunal"