📂
SEI 1019
  • Introduction
  • About These Notes
  • Syllabus
  • Development Workflow
    • Command Line
      • The Terminal
      • Filesystem Navigation
      • File Manipulation
      • Additional Topics
    • Intro to Git
      • Version Control
      • Local Git
      • Remote Git
      • Git Recipes
    • Group Collaboration
      • Git Workflows
      • Project Roles and Tools
    • VS Code Tips & Tricks
  • HTML/CSS
    • HTML
    • CSS Selectors
    • CSS Box Model and Positioning
      • Box Model
      • Display and Positioning
      • Flexbox
      • Grid
      • Flexbox & Grid Games
      • Floats and Clears
      • Additional Topics
    • Advanced CSS
      • Responsive Design
      • Pseudo-Classes/Elements
      • Vendor Prefixes
      • Custom Properties
      • Additional Topics
    • Bootstrap
    • CSS Frameworks
    • Accessibility
  • JavaScript
    • Primitives
    • Arrays
    • Objects
    • Control Flow
      • Boolean Expressions
      • Conditionals
      • Loops
      • Promises
    • Functions
      • Callbacks
      • Timing Functions
      • Iterators
    • DOM and Events
    • DOM Manipulation
    • HTML5 Canvas
    • How To Reduce Redundancy
    • (2019) JavaScript OOP
    • (2016) OOP with Classes
    • (1995) OOP with Prototypes
      • Constructors
      • Prototypes
    • Intro to TDD
    • Scoping
    • Inheritance
      • Prototypal Inheritance
      • Call, Apply, and other Functions
      • ES6 Inheritance
      • Resources
    • Custom Node Modules
    • Additional Topics
      • AJAX, Fetch, and Async/Await
      • AJAX w/JSON and Localstorage
        • AJAX w/JSON
        • Local Storage
      • Async module
      • Data Scraping
  • jQuery
    • Intro
      • DOM Manipulation
      • Reddit Practice
      • Styling
      • Events
    • Plugins
    • AJAX
  • APIs
    • Fetch
    • AJAX w/jQuery
    • AJAX w/Fetch
  • Databases
    • Intro to SQL
    • Advanced SQL
    • MongoDB
      • Intro to NoSQL
      • CRUD in MongoDB
      • Data Modeling
      • Intermediate Mongo
  • Node/Express
    • Node
      • Intro to Node
      • Node Modules
      • Node Package Manager (NPM)
    • Express
      • Intro to Express
        • Routes
        • Views
        • Templates
        • Layouts and Controllers
        • CRUD & REST
          • Get and Post
          • Put and Delete
      • APIs with Express (request)
      • APIs with Express (axios)
    • Sequelize
      • Terminology
      • Setup
      • Using Models
      • Seeding Data
      • Validations and Migrations
      • Resources
      • 1:M Relationships
      • N:M Relationships
    • Express Authentication
      • Research Components
      • Code Components
      • Auth in Theory
        • Sessions
        • Passwords
        • Middleware
        • Hooks
      • Auth in Practice
        • Create the User
        • User Signup
        • Sessions
        • User Login
        • Authorization and Flash messages
    • Testing with Mocha and Chai
    • Mongoose
      • Mongoose Associations
    • JSON Web Tokens
      • Codealong
    • Additional Topics
      • oAuth
      • Geocoding with Mapbox
      • Geocoding and Google Maps
      • Cloudinary
      • Websockets with Socket.io
      • SASS
  • Ruby
    • Intro to Ruby
    • Ruby Exercises
    • Ruby Classes
    • Ruby Testing with Rspec
    • Ruby Inheritance
    • Ruby Data Scraping
  • Ruby on Rails
    • Intro to Rails
    • APIs with Rails
    • Asset Pipeline
    • Rails Auth and 1-M
      • Auth Components
    • Rails N:M
    • ActiveRecord Polymorphism
    • Additional Topics
      • oAuth
      • SASS
      • Rails Mailers
      • Cloudinary
      • Jekyll
  • React (Updated 2019)
    • ES6+/ESNext
      • Const and Let
      • Arrow Functions
      • Object Literals and String Interpolation
      • ES6 Recap
      • ES6 Activity
    • Intro to React
      • Create React App
      • Components and JSX
      • Virtual DOM
      • Props
      • Dino Blog Activity
      • Nested Components
      • Lab: LotR
    • React State
      • Code-Along: Mood Points
      • Code-Along: Edit Dino Blog
      • Lab: Simple Calc
      • Lifting State
    • React Router
      • Browser History/SPAs
      • React Router (lesson and full codealong)
      • Router Lab
    • Fetch and APIs
      • APIs with Fetch and Axios
      • Fetch the Weather
    • React Hooks
    • React LifeCycle
      • Lab: Component LifeCycle
    • React Deployment
    • Additional Topics
      • React Frameworks
        • Material UI Theming
      • Typescript
        • More Types and Syntax
        • Tsconfig and Declaration Files
        • Generics with Linked List
      • Redux
      • TypeScript
      • Context API
      • React Native
  • Meteor
  • Deployment and Config
    • Installfest
      • Mac OSX
      • Linux
      • Git Configuration
      • Sublime Packages
    • Deploy - Github Pages
    • Deploy - Node/Sequelize
    • Deploy - Node/MongoDB
    • Deploy React
    • Deploy - Rails
      • Foreman (Environment Variables)
    • Deploy - AWS Elastic Beanstalk
    • Deploy - S3 Static Sites
    • Deploy - Django
    • Deploy - Flask
  • Data Structures and Algorithms
    • Recursion
    • Problem Solving - Array Flatten
    • Binary Search
    • Algorithm Complexity
    • Stacks and Queues
    • Bracket Matching
    • Ruby Linked Lists
      • Sample Code
      • Beginner Exercises
      • Advanced Exercises
    • JS Linked Lists
      • Sample Code
      • Beginner Exercises
      • Beginner Solutions
    • Hash Tables
    • Intro to Sorting
    • Insertion Sort
    • Bucket Sort
    • Bubble Sort
    • Merge Sort
    • Quick Sort
    • Heap Sort
    • Sorting Wrapup
    • Hashmaps
    • Trees and Other Topics
  • Python
    • Python Installation
    • Intro to Python
    • Python Lists
    • Python Loops
    • Python Dictionaries
    • Python Sets and Tuples
    • Python Cheatsheet
    • Python Functions
    • Python Classes
    • Python Class Inheritance
    • Intro to Flask
    • Intro to SQLAlchemy
      • Flask and SQLAlchemy
    • Using PyMongo
    • Intro to Django
    • CatCollector CodeAlong
      • URLs, Views, Templates
      • Models, Migrations
      • Model Form CRUD
      • One-to-Many Relations
      • Many-to-Many Relations
      • Django Auth
    • Django Cheatsheet
    • Django Auth
    • Django Polls App Tutorial
    • Django School Tool Tutorial
    • Django 1:M Relationships
    • Custom Admin Views
    • Data Structures and Algorithms
      • Recursion
      • Binary Search
      • Stacks and Queues
      • Linked Lists
      • Binary Trees
      • Bubble Sort
      • TensorFlow & Neural Networks
    • Adjacent Topics
      • Raspberry Pi
      • Scripting
  • Assorted Topics
    • History of Computer Science
    • Regular Expressions
    • Intro to WDI (Course Info)
    • Being Successful in WDI
    • Internet Fundamentals
      • Internet Lab
    • User Stories and Wireframing
      • Wireframing Exercise: Build an Idea
    • Post WDI
      • Learning Resources
      • Deliverables -> Portfolio
      • FAQ
  • Projects
    • Project 1
    • Project 2
    • Project 3
      • Project 3 Pitch Guidelines
    • Project 4
    • Past Projects
      • Project 1
      • Project 2
      • Project 3
      • Project 4
      • Portfolios
    • Post Project 2
    • MEAN Hackathon
      • Part 1: APIs
      • Part 2: Angular
    • Portfolio
  • Web Development Trends
  • Resources
    • APIs and Data
    • Tech Websites
    • PostgreSQL Cheat Sheet
    • Sequelize Cheat Sheet
    • Database Administration
  • Archived Section
    • (Archived) ReactJS
      • Intro to React
        • Todo List Codealong
        • Additional Topics
      • Deploy React
      • React with Gulp and Browserify
        • Setting up Gulp
        • Additional Gulp Tasks
      • React Router
        • OMDB Router
        • OMDB Search
        • Additional Resources
      • React Animations
        • CSS Animations
    • AngularJS
      • Intro to AngularJS
        • Components and SPA
        • Create an Angular App
      • Angular Directives and Filters
      • Angular Animation
      • Angular Bootstrap Directives
        • Bootstrap Modals
      • Angular $http
      • Angular Services
        • Service Recipes
        • ngResource
        • Star Wars Codealong
      • Angular Routing
      • Angular + Express
      • Angular Authentication
        • Additional Topics
      • Angular Components
      • Angular Custom Filters
      • Angular Custom Directives
Powered by GitBook
On this page
  • Objectives
  • Inheritance
  • Example
  • Binding to an interactive console with pry
  • A Guide through Animals

Was this helpful?

  1. Ruby

Ruby Inheritance

Objectives

  • Implement inheritance

  • Describe what has been inherited from one class to another

  • Compare and contrast inheritance in Ruby with Prototypical inheritance in Javascript

  • Utilize inheritance to reduce repetition

  • Utilize inheritance to model the world

  • Install pry using gem. Pry is an improved REPL for Ruby that allows for better debugging and lets you work interactively with pre-written scripts through the use of binding.pry

Quick Review

  1. What is a method? What is a class?

  2. What is an instance method?

  3. Why do we use a class?

Inheritance

Inheritance is used to indicate that one class will get most or all of its features from a parent class. Inheritance is useful for a couple reasons.

  • DRY - Don't Repeat Yourself & reuse code functionality

  • Faster implementation time

Example

class Rectangle

  def initialize(l, w)
    @length = l
    @width = w
  end

  def get_area
    @length * @width
  end

  def print_shape
    puts "This is a rectangle"
  end

end

class Square < Rectangle
  def initialize(s)
    super(s, s)
  end

  def print_shape
    puts "This is a rectangle and a square"
  end
end

Note from the example above...

  • In order to inherit from a class, we use the < keyword and specify the class we want to inherit from

  • In order to correctly inherit from Square, we need to call the parent class's initialize method. We can do so by using the super method.

    • If we forget to do this, class and instance variables in the parent will not be initialized

    • When you invoke the super method with arguments, Ruby sends a message to the parent of the current object, asking it to invoke a method of the same name as the method invoking super.

  • Once we inherit from another class, we can access methods and properties from the parent. In the case of this Square class, we also overrode the functionality of the print_shape method.

Binding to an interactive console with pry

You can use pry to halt the execution of your program and start an interactive console. This is a great debugging tool.

Create a few rectangles and a square at the end of your file. Write pry.binding to stop the program after the shapes are created. You must import this pry library by writing require.pry at the top of your program.

Install pry by running gem install pry in your terminal

require 'pry'

r1 = Rectangle.new(3, 4)
r2 = Rectangle.new(4, 7)
s1 = Square.new(3)

# halt the program just after the shapes are created
pry.binding

Now you can type expressions into the console and have them evaluated. Your console will look like this. Typing r1 and r2 shows the type of objects that exist in those variables. Typing r1.get_area executes the function and prints the result.

[1] pry(main)> r1
=> #<Rectangle:0x007fe85311f6f0 @height=4, @width=3>
[2] pry(main)> r2
=> #<Rectangle:0x007fe85311f6c8 @height=7, @width=4>
[3] pry(main)> r1.get_area
=> 12

Having access to a console like this is a great way to explore ruby with new pieces of code to make sure they work. Type things into the interactive console to figure out how you could calculate the area of a circle: Pi r squared.

Here's an example of me using the interactive console to try to find out how ruby's math module works, and where the value of Pi lives within it. Notice that it's totally ok to cause errors! The interactive console just prompts you to try again.

# is it called MATH?
[10] pry(main)> MATH
NameError: uninitialized constant MATH
from (pry):10:in `<main>'

# is it called math?
[11] pry(main)> math
NameError: undefined local variable or method `math' for main:Object
from (pry):11:in `<main>'

# finally found the proper Math object
[12] pry(main)> Math
=> Math

# where the heck does Pi exist?
[13] pry(main)> Math.pi
NoMethodError: undefined method `pi' for Math:Module
from (pry):13:in `<main>'

[14] pry(main)> Math.PI
NoMethodError: undefined method `PI' for Math:Module
from (pry):14:in `<main>'

[15] pry(main)> Math.Pi
NoMethodError: undefined method `Pi' for Math:Module
from (pry):15:in `<main>'

# hmm, I remember seeing this strange syntax.. there Pi is!!
[16] pry(main)> Math::PI
=> 3.141592653589793

A Guide through Animals

class Animal

  def initialize(kind)
    @kind = kind
    @state = "awake"
  end

  def eat(food)
    if @state == "awake"
      puts "NOM-nom!!"
      puts "(#{kind} has eaten #{food})"
    else
      puts "SLEEPING"
    end
    self
  end

  def sleep
    @state = "sleeping"
    self
  end

  def wake
    @state = "awake"
    self
  end
end

class Person < Animal
  def initialize(age, gender, name)
    super("Human")
    @age = age
    @gender = gender
    @name = name
  end
end

Single Inheritance vs Multiple Inheritance

  • In Ruby, a class can only inherit from a single other class. It cannot inherit from multiple classes.

    • Think about it. What are some benefits and disadvantages to single & multiple inheritance?

Exercise

Create a Mammal class, Cat class, and Dog class. Have Cat and Dog inherit from Mammal. Include some attributes for each class and a method for mammal.

Make cats fall asleep when they're fed tuna. Make dogs fall asleep when they're fed a bone.

PreviousRuby Testing with RspecNextRuby Data Scraping

Last updated 4 years ago

Was this helpful?