Skip to content

Instantly share code, notes, and snippets.

@bswinnerton
Last active September 3, 2019 01:21
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save bswinnerton/10009403 to your computer and use it in GitHub Desktop.
Save bswinnerton/10009403 to your computer and use it in GitHub Desktop.

Back End Web Development

Ruby

Data types

  1. String - denoted by single or double quotes
    e.g. "Brooks", 'brooks'

  2. Integer (aka Fixnum) - A whole number
    e.g. 1, 42

  3. Float - A decimal
    e.g. 3.14

  4. Symbol - very similiar to a string, but more efficient to the computer. Always lower case
    e.g. :brooks, :name

  5. Array - A list of data objects
    e.g. ['Brooks', 'Danielle', 'Otto', 'Luna']

  6. Hash - Similar to an Array, but instead has keys that can be used to retrieve a value
    e.g. { name: 'Brooks', roommate: 'Danielle', cats: ['Otto', 'Luna']}

  7. Boolean - A true / false value

Variables

Variables are used to store data types into the memory of the computer so that they can be referenced later. Always all lowercase, and with underscores:

name = 'Brooks'
home_address = '1234 Willoughby Ave'
age = 24
cats = [ 'Otto', 'Luna' ]
home = { name: name, address: home_address, age: age, cats: cats }

String interpolation

Interpolation can be used to concatenate a string and another data type. By using #{}, you can coerce a data type into a string (under the hood it calls .to_s

name = 'Brooks'
age = 24
"Name: #{name}, Age: #{age}"

As opposed to:

name = 'Brooks'
age = 24
"Name: #{name}, Age: " + age

Methods

A collection of code that lives inside a def and end that can be reused. They can also "take in" parameters, which are variables that change scope inside the method.

The idea of scope is an important one. Scope says that variables created inside a method, stay in a method. Once a method stops running, they are no longer available to the program.

my_name = 'Brooks'

def greet(name)
  puts "Hello #{name}"
end

greet(my_name)

Base ruby methods

Some methods are given to you for free like Ruby. Once of which is puts, which stands for "put string", that prints something out to the screen (but doesn't return a value). Another is gets, which awaits user input from the terminal.

Conditions

Conditionals are the lifeblood of programming. In ruby, we use if, elsif, and else:

name = 'BEWD Student'
if name == 'BEWD Student'
  puts "You're awesome!"
elsif name == 'Otto'
  puts "You're a cat"
else
  puts "You're not awesome or a cat"
end

We also use conditions like
Less than: <
Less than or equal to: <=
Greater than: >
Greater than or equal to: >=
Not equal to: !=
Modulus: %

And you can join multiple conditions with
And: &&
Or: ||

Iteration

Iteration allows you to loop over enumerable objects

Each

Iterates and returns the object passed to it (in the below example, house_members is returned, but the "lives at" is still printed to the screen)

house_members = [ 'Brooks', 'Danielle', 'Otto', 'Luna' ]
house_members.each do |member|
  puts "#{member} lives at 1234 Willoughby Ave"
end

Map

Iterates and returns the object that is last returned in the block (in the below example, a new hash with only the cats key and value is returned)

people = [
  { name: 'Danielle', cats: [ 'Otto' ] },
  { name: 'Brooks', cats: [ 'Luna' ] }
]
cats = people.map do |person|
  { cats: person[:cats] }
end

APIs

# Require the libraries needed to talk to the internet (JSON to convert a string to ruby data objects), rest-client to talk to the internet
require 'json'
require 'rest-client'

# A URL that we want to grab off the internet
url = 'http://reddit.com/.json'

# Ask the RestClient library to get the url from the internet
response = RestClient.get(url)
# Take the response that we got from RestClient and parse it with JSON
parsed_response = JSON.parse(response)

# At this point we have a lot of data, the only things that we care about are the title, author and url. Using map we can only return those three values that we care about
posts = parsed_response['data']['children'].map do |post|
  {
    title: post['data']['title'],
    author: post['data']['author'],
    url: post['data']['url']
  }
end

# Output to the screen the attributes that we care about for all the posts we got from the internet
posts.each do |post|
  puts "Title: #{post[:title]}"
  puts "Author: #{post[:author]}"
  puts "URL: #{post[:url]}"
  puts
end

Classes

Classes are a way of organizing our code. They are very similar to hashes where you can store attributes, but they offer something that hashes don't: a way of adding methods to only one particular set of data type. They usually look like this:

class Cat
  attr_accessor :name, :color, :favorite_spot

  def initialize(name, color, favorite_spot)
    @name = name
    @color = color
    @favorite_spot = favorite_spot
  end

  def meow
    "meow"
  end

  def eat
    "chomp chomp"
  end
end

Let's break this apart into the what each of these lines are doing

  1. attr_accessor: this magical line actually does the following:
def name
  @name
end

def name=(name)
  @name = name
end

These are called a "getter" and "setter", respectively. The getter (def name), sets an instance variable of the same name as the symbol that you're passing to attr_accessor and allows an instance of a class to retrieve it's value. The setter (def name=(name)) as you probably guessed it, allows you to set an instance variable as the same name as the symbol passed to the attr_accessor.

  1. Next up, you see the def initialize(name, color). I like to think of this as the same thing as def self.new(name, color) (note: that doesn't actually work, it's just how I like to think about it), meaning that you call it when you type Cat.new but pass it the initial state of what the instance should have; e.g. Cat.new('Otto', 'grey'). This sets the initial object with the name and color right off the bat.

  2. Lastly, there are two methods that simply return a string so that you can call them with something like:

my_cat = Cat.new('otto', 'grey')
puts my_cat.meow

Inheritance

You will often find that you have similarity between classes. Rather than writing the same code over and over again, we like to keep things DRY (don't repeat yourself). There are a few different ways of solving this. The first, being inheritence: where one class inherits from another. It looks like this:

class Animal
  attr_accessor :name, :color

  def initialize(name, color)
    @name = name
    @color = color
  end

  def eat
    "chomp chomp"
  end
end

class Cat < Animal
  attr_accessor :favorite_spot

  def initialize(name, color, favorite_spot)
    super(name, color)
    @favorite_spot = favorite_spot
  end

  def meow
    "meow"
  end
end

This is pretty straight-forward. To signify that a class has a parent class, we simply append < Animal to the class definition line.

It starts to get tricky with super. super is a way to call the parent's method of the same name. If the parent method takes in parameters, you'll have to be sure to pass in the same number of parameters as we do above with super(name, color).

Modules

Modules are another way of sharing code between two classes. Modules are typically used when you have classes that aren't related by nature, but they do share the same sort of functionality. They look like this:

module Annoyingable
  def annoying
    "I'm hungry " * 10
  end
end

class Cat
  include Annoyingable
  attr_accessor :name, :color, :favorite_spot

  def initialize(name, color, favorite_spot)
    @name = name
    @color = color
    @favorite_spot = favorite_spot
  end
end

class Baby
  include Annoyingable
  attr_accessor :name

  def initialize(name)
    @name = name
  end
end

We simply use the include keyword to "mix-in" the functionality that is defined inside of the module.

Then we can do the following:

otto = Cat.new('Otto', 'grey', 'Nice clothes')
brooks = Baby.new('Brooks')

puts otto.annoying
puts brooks.annoying
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment