Ruby Cheat Sheet : For Beginners

Mr. Unity Buddy's photo
Mr. Unity Buddy
·May 26, 2021·

13 min read

Ruby Cheat Sheet : For Beginners

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Hello, buddies! Today we're going to learn all the basics of our new trending language, Ruby.


Introduction

Ruby is a powerful, flexible programming language you can use in web/Internet development, to process text, to create games, and as part of the popular Ruby on Rails web framework. Ruby is: High-level, meaning reading and writing Ruby is really easy—it looks a lot like regular English!

Interpreted, meaning you don’t need a compiler to write and run Ruby. You can write it here at Codecademy or even on your own computer (many are shipped with the Ruby interpreter built in—we’ll get to the interpreter later in this lesson).

Object-oriented, meaning it allows users to manipulate data structures called objects in order to build and execute programs. We’ll learn more about objects later, but for now, all you need to know is everything in Ruby is an object.

Easy to use. Ruby was designed by Yukihiro Matsumoto (often just called “Matz”) in 1995. Matz set out to design a language that emphasized human needs over those of the computer, which is why Ruby is so easy to pick up


STRINGS (4).png In Ruby, a variable is a place to store values of almost any type including Integer, Boolean, String, Array, and Hashes.

Each variable has its own name which cannot begin with a capital letter or a number and we use the equal sign for assigning a value to that variable.

The variable declaration does not require that you mention a specific data type.

The following program declares myvar variable and assigns the value 48.

myvar = 48

We don't don’t need to mention its type as C++ and ruby will know its type automatically.


STRINGS (12).png put and print commands can be used to display text in the console.

put "I am Unity Buddy"
print "This command is same as put"

STRINGS (5).png Commenting code helps programmers write free text that is commonly used to explain the code written, or can even be used to add TODO’s to the code. There are two types of comments that can be written in Ruby:

  • Single line comments start with a #.
  • Multi line comments start with =begin and end with =end.
    # This is a single line comment
    =begin
    This is 
    a multiline comment
    =end
    

STRINGS.png Strings in Ruby are a sequence of characters enclosed by single quotation marks ‘ ’ or double quotation marks “ ”

  • Double-quote strings allow escaped characters such as \n for newline, \t for the tab, etc.
    puts("This is a simple string")
    puts("This string has a double quote: \". It is escaped")
    puts("Double-quote strings allow escaped characters such as \n for newline, \t for tab, etc.")
    
    Output will be,
    This is a simple string
    This string has a double quote: ". It is escaped
    Double-quote strings allow escaped characters such as
    for newline,    for tab, etc.
    
    The following table shows the various escape situation:

image.png

Expression Substitution

Expression substitution is a means of embedding the value of any Ruby expression into a string using #{ and } −

x, y, z = 12, 36, 72
puts "The value of x is #{ x }."
puts "The sum of x and y is #{ x + y }."
puts "The average was #{ (x + y + z)/3 }."

This program will give us,

The value of x is 12.
The sum of x and y is 48.
The average was 40.

String Built-in Methods

We need to have an instance of String object to call a String method. Following is the way to create an instance of String object −

new [String.new(str = "")]

This will return a new string object containing a copy of str. Now, using str object, we can all use any available instance methods. For example −

#!/usr/bin/ruby

myStr = String.new("I am 1101 years old")
foo = myStr.downcase

puts "#{foo}"

Output,

I am 1101 years old

STRINGS (3).png In Ruby, your information (or data) can come in different types. There are three data types in Ruby that we’re interested in right now: Numeric (any number), Boolean (which can be true or false), and String (words or phrases like "Unity Buddy Is Good!").

Reminder: never use quotation marks (‘ or “) with booleans, or Ruby will think you’re talking about a string (a word or phrase) instead of a value that can be true or false. It’s also important to remember that Ruby is case-sensitive (it cares about capitalization).

my_num =  25   

my_boolean =  true   

my_string = "Buddy"  

puts my_num
puts my_boolean
puts my_string

Numeric data types in Ruby

In Ruby, the Numeric data type represents numbers including integers and floats.

# Integer value
x = 1

# Float value
y = 1.2

Boolean Data Types in Ruby

In Ruby, in order to represent values of truth about specific statements, we use Boolean variables. Boolean variables values are either true or false.

# Boolean true variable
year2021 = true

# Boolean false variable
year2020 = false

STRINGS (1).png

if conditional [then]
   code...
[elsif conditional [then]
   code...]...
[else
   code...]
end

if expressions are used for conditional execution. The values false and nil are false, and everything else are true. Notice Ruby uses elsif, not else if nor elif.

Executes code if the conditional is true. If the conditional is not true, code specified in the else clause is executed.

An if expression's conditional is separated from code by the reserved word then, a newline, or a semicolon.

x = 1
if x > 2
   puts "x is greater than 2"
elsif x <= 2 and x!=0 # != means `not equal`
   puts "x is 1"
else
   puts "I can't guess the number"
end

Output will be,

x is 1

unless Statement

unless conditional [then]
   code
[else
   code ]
end

Executes code if conditional is false. If the conditional is true, code specified in the else clause is executed. Example :

x = 1 
unless x>=2
   puts "x is less than 2"
 else
   puts "x is greater than 2"
end
# Outputs x is less than 2

case Statement

case expression
[when expression [, expression ...] [then]
   code ]...
[else
   code ]
end

Compares the expression specified by case and that specified by when using the === operator and executes the code of the when clause that matches.

The expression specified by the when clause is evaluated as the left operand. If no when clauses match, case executes the code of the else clause.

A when statement's expression is separated from code by the reserved word then, a newline, or a semicolon. Thus −

case expr0
when expr1, expr2
   stmt1
when expr3, expr4
   stmt2
else
   stmt3
end

is basically similar to,

_tmp = expr0
if expr1 === _tmp || expr2 === _tmp
   stmt1
elsif expr3 === _tmp || expr4 === _tmp
   stmt2
else
   stmt3
end

Example :

$age =  5
case $age
when 0 .. 2
   puts "baby"
when 3 .. 6
   puts "little child"
when 7 .. 12
   puts "child"
when 13 .. 18
   puts "youth"
else
   puts "adult"
end
# Output : little child

I have a little advice here. Don't stress about what you don't understand.


Just Relax!

Use your arrow keys..


STRINGS (13).png Ruby supports a rich set of operators, as you'd expect from a modern language. Most operators are actually method calls. For example, a + b is interpreted as a.+(b), where the + method in the object referred to by variable a is called with b as its argument.

As any language, there are main 5 types of operators.

  • Arithmetic Operators : Arithmetic operators take numerical values as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/).
  • Comparison Operators : Comparison operators take simple values (numbers or strings) as arguments and used to check for equality between two values.
  • Assignment Operators : In Ruby assignment operator is done using the equal operator "=". This is applicable both for variables and objects, as strings, floats, and integers are actually objects in Ruby, you're always assigning objects.
  • Logical Operators : The standard logical operators and, or and not are supported by Ruby. Logical operators first convert their operands to boolean values and then perform the respective comparison.
  • Bitwise Operators : In Ruby, Bitwise operators allow to operate on the bitwise representation of their arguments.

Arithmetic and Comparison Operators take main parts in most of the languages.

Arithmetic operations

In Ruby, we can use arithmetic operators to evaluate mathematical expressions. The most common Ruby arithmetic operators are addition (+), subtraction (-), division(/), multiplication(), exponentiation(*) and modulo(%).

print 1+3
# Addition: output 4

print 1-2
# Subtraction: output -1

print 9/3
# Division: output 3

print 2*3
# Multiplication: output 6

print 2**3
# Exponentiation: output 8

print 16%9
# Modulo: output 7

Parallel Assignment

Ruby supports the parallel assignment of variables which can be done in a single operation. Therefore you can declare several variables to the left as an assignment operator and several values to the right. The order of the values to the right must be same to the variables on the left. See the following syntax :

l1, l2, l3 = "Python", "Ruby", "PHP"

STRINGS (7).png

While loop

while conditional [do]
   code
end

Executes code only while conditional is true. A while loop's conditional is separated from code by the reserved word do, a newline, backslash \, or a semicolon ;.

$i = 0
$num = 5

while $i < $num  do
   puts("Inside the loop i = #$i" )
   $i +=1
end

This will outputs,

Inside the loop i = 0
Inside the loop i = 1
Inside the loop i = 2
Inside the loop i = 3
Inside the loop i = 4

until Statement

until conditional [do]
   #code
end

Executes code while conditional is false. An until statement's conditional is separated from code by the reserved word do, a newline, or a semicolon. As an example,

$i = 0
$num = 5
begin
   puts("Inside the loop i = #$i" )
   $i +=1;
end until $i > $num

=begin
Output : Inside the loop i = 0
Inside the loop i = 1
Inside the loop i = 2
Inside the loop i = 3
Inside the loop i = 4
Inside the loop i = 5
=end

for loops

for variable [, variable ...] in expression [do]
   code
end

Executes code once for each element in expression. Let's take,

for i in 0..5
   puts "Value of local variable is #{i}"
end

Here, we have defined the range 0..5. The statement for i in 0..5 will allow i to take values in the range from 0 to 5 (including 5). This will produce the following result −

Value of local variable is 0
Value of local variable is 1
Value of local variable is 2
Value of local variable is 3
Value of local variable is 4
Value of local variable is 5

next Statement

Jumps to the next iteration of the most internal loop. Terminates execution of a block if called within a block (with yield or call returning nil).

for i in 0..5
   if i < 2 then
      next
   end
   puts "Value of local variable is #{i}"
end

=begin
Value of local variable is 2
Value of local variable is 3
Value of local variable is 4
Value of local variable is 5
=end

retry Statement

If retry appears in rescue clause of begin expression, restart from the beginning of the begin body.

begin
   do_something # exception raised
rescue
   # handles error
   retry  # restart from beginning
end

If retry appears in the iterator, the block, or the body of the for expression, restarts the invocation of the iterator call. Arguments to the iterator is re-evaluate.


STRINGS (6).png

  • gets.chomp is used to take input from user.
  • print can be used instead for puts to print without a new line.
    print "How old are you ? "
    age = gets.chomp
    print "How tall are you ?"
    height = gets.chomp
    puts " You are #{age} year old and your height is #{height} cms"
    

STRINGS (8).png Ruby arrays are ordered, integer-indexed collections of any object. Each element in an array is associated with and referred to by an index.

Array indexing starts at 0, as in C or Java. A negative index is assumed relative to the end of the array --- that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.

Ruby arrays can hold objects such as String, Integer, Fixnum, Hash, Symbol, even other Array objects. Ruby arrays are not as rigid as arrays in other languages. Ruby arrays grow automatically while adding elements to them.

Creating Arrays

There are many ways to create or initialize an array. One way is with the new class method

names = Array.new
# To set size of an array at the time of creating array −
names = Array.new(20)

# You can assign a value to each element in the array as follows −
names = Array.new(4, "mac")
puts "#{names}"

Array Built-in Methods

We need to have an instance of Array object to call an Array method. As we have seen, following is the way to create an instance of Array object −

Array.[](...) [or] Array[...] [or] [...]

This will return a new array populated with the given objects. Now, using the created object, we can call any available instance methods. For example −

digits = Array(0..9)
num = digits.at(6)
puts "#{num}"
# Output : 6

STRINGS (11).png A Hash is a collection of key-value pairs like this: "employee" = > "salary". It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index.

The order in which you traverse a hash by either key or value may seem arbitrary and will generally not be in the insertion order. If you attempt to access a hash with a key that does not exist, the method will return nil.

To create Hashes,

months = Hash.new

STRINGS (10).png Ruby methods are very similar to functions in any other programming language. Ruby methods are used to bundle one or more repeatable statements into a single unit.

Method names should begin with a lowercase letter. If you begin a method name with an uppercase letter, Ruby might think that it is a constant and hence can parse the call incorrectly.

Methods should be defined before calling them, otherwise Ruby will raise an exception for undefined method invoking.

def method_name [( [arg [= default]]...[, * arg [, &expr ]])]
   expr..
end

So, you can define a simple method as follows −

def print_data(value)
  puts value 
end

You can represent a method that accepts parameters and arguments like this −

def add_values(num1, num2)
  return num1 + num2
end

Class Methods

When a method is defined outside of the class definition, the method is marked as private by default. On the other hand, the methods defined in the class definition are marked as public by default. The default visibility and the private mark of the methods can be changed by public or private of the Module.

Whenever you want to access a method of a class, you first need to instantiate the class. Then, using the object, you can access any member of the class.

Ruby gives you a way to access a method without instantiating a class. Let us see how a class method is declared and accessed −

class Accounts
   def reading_charge
   end
   def Accounts.return_date
   end
end

See how the method return_date is declared. It is declared with the class name followed by a period, which is followed by the name of the method. You can access this class method directly as follows −

Accounts.return_date

So buddies, these are the basics you should know about Ruby. Thanks for reading this long cheat sheet(I did my best to make it short') and Happy Coding with Ruby!

 
Share this