Ruby

Ruby is a high-level, interpreted, general-purpose programming language, designed with an emphasis on programming productivity and simplicity.

Running or Executing a Ruby File

ruby ruby_program.rb

Ruby Basics

Including External Libraries & Files

require 'pry'

require './lib/file.rb'

Printing Output

puts 'Hello from the terminal!'

print 'This prints on the same line'

Comments

# This is a comment in Ruby
# Longer comments can be made using multiple lines 

Variables & Data Types

# Strings

letter = 'C'
sentence = "Hi, I'm a long string!"

# Integers (Whole Numbers)

age = 29
birthday_month = 7

# Floats (Decimal Numbers)

checking_amount = 64.86
savings_amount = 1256.90

# Booleans

is_a_programmer = true
is_employed = false
# Local Variables
# Scope: Available within whichever code block they are defined in.

local = "Hi, I'm a local variable!"

# Instance Variables
# Scope: Available within the object's scope, and are created in the initialize method.

@instance = 25

# Class Variables (Not very common)
# Scope: Available within the class block or any sub-class block.

@@class = [1, 2, 3, 4]

# Global Variables (Not very common)
# Scope: Available within the whole Ruby program.

$global = {
  one: 'First',
  two: 'Second'
}

Operators

Assignment Operators

  • = - is assigned to
  • += - add and assignment
  • -= - subtract and assignment
  • *= - multiply and assignment
  • /= - divide and assignment
  • %= - modulus and assignment (remainder of)
  • **= - exponential and assignment (to the power of)

Arithmetic Operators

  • + - add
  • - - subtract
  • * - multiply
  • / - divide by (be wary of integer vs float)
  • % - modulus (remainder of)
  • ** - exponential (to the power of)

Relational Operators

  • < - less than
  • <= - less than or equal to
  • > - more than
  • >= - more than or equal to
  • == - equals
  • != - does not equal

Logical Operators

  • || - or
  • && - and

Ternary Operators

  • ? : - boolean expression ? "It's true!" : "Nah, it's false."

Range Operators

  • .. - creates a range from the start to the end point (inclusive)
  • ... - creates a range from the start to the end point (exclusive)

Data Structures

Arrays

# Creating a new Array

empty_array = []                 # Creates empty array
empty_array = Array.new          # Creates empty array
empty_array = Array.new(8, 0)    # Creates 8 elements with a default value of 0

# Elements in an array can be any type of object

example = ["first", 5, false, 567.305, "woah", true, 84, 0.43, [1, 2, 3], {color: red}]

# Usually, arrays hold the same data type

arr_integers = [12, 78, 605, 5829, 2365]
arr_floats = [38.43, 18.36, 237.24, 555.23, 2060.60]
arr_strings = ["Hello", "this", "is", "an", "array"]
arr_bools = [true, false, true, true, false]

Hashes

# Creating a new Hash

empty_hash = {}             # Creates empty hash
empty_hash = Hash.new       # Creates empty hash
empty_hash = Hash.new(0)    # Default value is 0

# Keys and values can be any type of data or data structure

example = {
  "string_value" => "this value is a string",
  "array_value" => ["this", "value", "is", "an", "array"],
  3 => "this values' key is an integer",
  "boolean_value" => true,
  true => 1.5
}

grocery_list = {
  "bananas" => 4,
  "apples" => 6,
  "onions" => 2,
  "tortillas" => 2,
  "tacos" => ["beans", "cheese", "beef", "salsa"]
}

bob = {
  age: 26,
  name: 'Billy Bob',
  hometown: 'Houston, Texas',
  married: false
}

Conditionals

if boolean
  # Code if boolean is true
end
if boolean
  # Code if boolean is true
else
  # Code if boolean is false
end
if boolean1
  # Code if boolean1 is true
elsif boolean2
  # Code if boolean1 is false and boolean2 is true
else
  # Code if both boolean1 and boolean2 are false
end

Loops

# Times Loop

3.times do
  puts 'x'
end

5.times do |i|
  puts i
end
# For Loop

for i in [1, 15, 653, 54, 245] do
  puts i
end

for i in (0..5) do # Prints 6
  puts i
end

for i in (0...5) do # Prints 5
  puts i
end
# While Loop

switch = 0

while switch < 5 do
  puts switch
  switch += 1
end
# Infinite Loop

switch = 0

loop do
  puts switch
  switch += 1

  break if switch >= 5
end

Classes & Objects

Classes & Objects

An object is an instance of a class. The class is a blueprint, the instance is a specific version of that blueprint.

class Person
  # Constructor
  def initialize(name, age)
    @name = name
    @age = age
  end

  # Instance method
  def introduce
    "Hi, my name is #{@name} and I am #{@age} years old."
  end

  # Another method
  def birthday
    @age += 1
    "Happy birthday! I am now #{@age}."
  end
end

# Using the class
person = Person.new("Alice", 30)
puts person.introduce
puts person.birthday

Modules

Modules are somewhat similar to classes - they are things that hold methods. However, modules can't be instantiated. Modules let you share methods between classes. Modules can be included into classes, and this makes their methods available on the class, just as if we'd copied and pasted these methods over to the class definition. This is useful if we have methods that we want to reuse in certain classes, but keep them in a central place, so we do not have to repeat them everywhere (DRY - Don't Repeat Yourself).

module Cream
  def cream?
    true
  end
end

class Cookie
  include Cream
end

cookie = Cookie.new
p cookie.cream?

Read more here: https://ruby-for-beginners.rubymonstas.org/advanced/modules.html

Functions & Methods

def square(n)
  n * n
end

puts square(5) # 25

Reading from CSV

require 'csv'

data = File.read('data/people.csv')
parsed_data = JSON.parse(data)

parsed_data.each do |person|
  puts person["first_name"]
end

Reading from JSON

require 'json'

data = File.read('data/people.json')
parsed_data = JSON.parse(data)

parsed_data.each do |person|
  puts person["first_name"]
end