Booking options
£67.99
£67.99
On-Demand course
31 hours 27 minutes
All levels
Unlock the power of coding with our all-inclusive Ruby course. Whether you're starting from scratch or elevating your programming skills, this course is tailored for a seamless learning curve in Ruby 3.2.
'Learn to Code with Ruby" is a meticulously crafted educational experience, designed to take you from beginner to proficient in the world of programming. Your learning adventure begins with the basics of installation and configuration on various operating systems, followed by an exploration of Ruby's object-oriented principles. As you progress, you'll delve into the core of programming with hands-on sessions on variables, data types, and control structures. Our approach is to build your skills progressively, ensuring that each concept is understood profoundly before moving to the next. The course is designed to simulate a real-world coding environment, with practical exercises that encourage problem-solving and critical thinking. Beyond the syntax and semantics, we emphasize why programming is a critical skill in today's technology-driven landscape. Ruby not only opens doors to software development but also lays a strong foundation for web development with Ruby on Rails. As you move through the course, you'll experience the satisfaction of creating functional code that evolves with complexity. By the end of your journey, you'll be well-equipped with the knowledge and skills to tackle real-world programming challenges with confidence and creativity. Please refer to the GH repository for all course files and codes.
Install and configure Ruby on Mac OS and Windows
Understand basic programming concepts like variables, arithmetic, and output
Manipulate strings, numbers, and Booleans in Ruby
Work with Ruby collections such as ranges, arrays, and hashes
Implement blocks, procs, and lambdas
Master object-oriented programming with classes, modules, and inheritance
This course is ideal for novice programmers seeking an introduction to an easy, user-friendly programming language, as well as for intermediate coders eager to delve deeper into Ruby. It's also perfectly suited for web developers looking to understand the underlying principles of Ruby on Rails.
This is a comprehensive beginner-friendly course to learn coding with Ruby. The course offers more than 30+ hours of video tutorials, 250+ lectures, and dozens of quizzes and exercises to test your knowledge as you proceed through the course.
Learn to program using Ruby and solve popular coding challenges and algorithms with Ruby * Hands-On coding and quizzes to reinforce learning and build real-world skills * Over 40 hours of video content and 250+ lectures, covering everything from basics to advanced topics
https://github.com/PacktPublishing/Learn-to-Code-with-Ruby-
Boris Paskhaver is a New York City-based software engineer, author, and Udemy instructor with a unique journey into tech. Graduating from NYU in 2013 with a degree in Business Economics and Marketing, he initially worked in various roles, including business analyst and data analyst, at several companies. His coding journey began accidentally while building projects with Python and JavaScript, leading him to passionately pursue programming. Without formal computer science education, Boris completed App Academy's full-stack web development bootcamp, diving headfirst into web development. As an instructor, Boris focuses on creating comprehensive, easy-to-understand courses, addressing the challenges he faced learning to code. He's driven by the intersection of technology and education, aiming to make programming accessible to all. Boris brings this passion to his teaching, helping others unlock the potential of coding.
1. Introduction and Installation
Embark on your Ruby journey with an overview, delve into OOP principles, and set up your development environment. Extend VSCode with Ruby extensions, write your first program, and explore IRB. Optionally review key concepts in the concluding section.
1. Welcome to Ruby Welcome to Learn to Code with Ruby! In this lesson, we introduce the language, its history, and some of its advantages/disadvantages relative to other languages. |
2. Object-Oriented Programming Learn about object-oriented programming (OOP), a paradigm that views a software program as a collection of objects that interact with one another. Practice applying OOP principles to real-world objects. |
3. macOS - Access and Work with the Terminal In this lesson, we access the Terminal application on a Mac, which is used to issue text commands to the operating system. We explore popular commands like pwd, ls, and cd to traverse directories and explore their contents. |
4. macOS - Install XCode Command Line Tools In this lesson, we'll install the XCode Command Line Tools, a technical prerequisite for installing Ruby on a macOS computer. |
5. macOS - Install Homebrew In this lesson we install Homebrew, a software package manager for macOS. We run Homebrew from our Terminal and use it to download/install applications. |
6. macOS - Install rbenv In this lesson, we install the rbenv Ruby version manager, which enables us to download and install multiple versions of Ruby on the same machine. |
7. macOS - Install Ruby In this lesson, we use rbenv to install Ruby on our macOS operating systems. Important Note, Ruby 3.3 is the latest version of the language as of January 2024. For most software, a greater version number indicates a more modern release. For example, Ruby 3 is newer than Ruby 2 and Ruby 3.3 is newer than Ruby 3.2. If you see a more modern version of Ruby available (i.e. a greater version number) than what it is shown in the installation videos, feel free to install it. |
8. macOS - Install VSCode Text Editor In this lesson, we download Visual Studio Code, the free text editor in which we'll be writing our Ruby code throughout the course. We also discuss the benefits of using such a tool. |
9. Windows - Access and Work with PowerShell In this lesson, we introduce the PowerShell command-line application and some common commands including ls for listing files/folders and cd for directory navigation. |
10. Windows - Figure Out if System is 32-bit or 64-bit In this lesson, we use our system settings to determine if our Windows version is 32-bit or 64-bit. |
11. Windows - Install Ruby In this lesson, we walk through the process of installing Ruby on a Windows machine. We also use Powershell to confirm the language was installed properly. Important Note, Ruby 3.3 is the latest version of the language as of January 2024. For most software, a greater version number indicates a more modern release. For example, Ruby 3 is newer than Ruby 2 and Ruby 3.3 is newer than Ruby 3.2. If you see a more modern version of Ruby available (i.e. a greater version number) than what it is shown in the installation videos, feel free to install it. |
12. Windows - Install VSCode Text Editor In this lesson, we download Atom, the text editor in which we'll be writing our code throughout the course. We also discuss the benefits of using such a tool. |
13. Install VSCode Extensions Download and install the Ruby and Code Runner VSCode extensions for the Visual Studio Code text editor. |
14. Write First Ruby File and Run with Code Runner In this lesson, we write our first Ruby program, which outputs the text Hello World to the screen. |
15. Write First Ruby File and Run with Terminal or PowerShell In this lesson, we learn how to run our Ruby file using the ruby program from our Terminal. To follow along please refer to the documentation and code files available here: https://github.com/PacktPublishing/Learn-to-Code-with-Ruby-/tree/main |
16. Interactive Ruby (IRB) In this lesson, we dive into Interactive Ruby (IRB), a REPL (Read Evaluate Print Loop) program for playing around with the Ruby programming language. |
17. Section Review [SLIDES] In this optional lesson, we'll review the concepts introduced in this course section including: |
2. Getting Started
Dive into Ruby basics with puts, escape characters, and print method. Learn about p method, comments, multiline comments, integers, arithmetic, and string concatenation. Introduce TypeError and review the section.
1. The puts Method In this lesson, we'll learn more about the puts method, which outputs text to the Terminal/output when the program runs. The puts method adds a line break to the end of the output. Like other methods in Ruby, it can be invoked with and without parentheses. We can also use commas to output multiple elements with the put method; Ruby will separate each one with a line break. |
2. Escape Characters In this lesson, we'll introduce escape characters, which are special symbols we can use in a Ruby string. Escape characters add special effects like line breaks, tabs, and symbols/characters to a string. We escape the expected pattern of output, which is Ruby outputting the literal characters that we've typed. |
3. The print Method In this lesson, we introduce the print method, another way to output text to the screen. The print method is similar to puts but it does not add a line break to the end of the output. |
4. The p Method In this lesson, we learn about the p method, which outputs a technical version of the object/output. For example, the p method will print a string with double quotes around the content. It exists primarily for the benefit of developers. |
5. Comments In this lesson, we'll learn how to use comments to ask Ruby to ignore specific lines of code. We create a comment with a hashtag/octothorpe (#) symbol. We can place the hashtag at the beginning of a line or after a line of valid Ruby code. Comments enable developers to leave explanations, metadata, annotations, diagrams, jokes, and more in their program. |
6. Multiline Comments In this lesson, you'll how to create multiline comments using =begin and =end. Ruby will treat any content between the two keywords as part of the comment. |
7. Integers and Floating Point Numbers In this lesson, we'll discuss the differences between integers and floating-point numbers and their syntax in Ruby. |
8. Basic Arithmetic in Ruby In this lesson, we'll learn the symbols for mathematical operations including addition, subtraction, multiplication, division, and modulo. |
9. String Concatenation In this lesson, we'll learn how to concatenate (join) two strings together using the + operator. |
10. Intro to Exceptions: TypeError In this lesson, we'll learn about errors/exceptions in Ruby including TypeError, which Ruby raises when we provide an invalid type of object for an operation. |
11. Section Review [SLIDES] Review everything we learned in this section of the course including output methods, comments, exceptions, concatenation, and more. |
3. Variables
Focus on variables with introduction, declaration, and understanding the NameError exception. Explore parallel variable assignment, swapping values, assignment shortcuts, constants, and review the section.
1. Variables [SLIDES] In this lesson, we'll learn about variables. A variable is a name we assign to a value in our program that is subject to change over time. |
2. Declaring Variables In this lesson, we practice declaring various variables in a .rb file and using them in expressions throughout the program. The variable syntax declaration begins a name, then an equal sign, and the value/object to assign that name to. |
3. Exceptions: NameError In this lesson, we'll learn about the NameError exception, which Ruby raises when it cannot recognize a name in your program. |
4. Parallel Variable Assignment In this lesson, we'll learn how to declare multiple variables and provide initial values to them on a single line. |
5. Swapping Variable Values In this lesson, we'll learn how to swap two variables (invert the values they store). |
6. Assignment Shortcuts In this lesson, we'll learn several shortcuts to perform an operation on a variable's value and assign the result back to the original variable. |
7. Constants In this lesson, we'll learn to declare constants in Ruby. A constant is a name for a value that will not change over the program's execution. |
8. Section Review [SLIDES] Review everything we've learned in this course section including variables, constants, parallel variable assignment, and more! |
4. Object Methods
Embark on object methods with an introduction, exploring Integer methods, handling NoMethodError exceptions, and understanding method chaining, inspect method, and the nil object. Dive into string interpolation, gets method, class method, conversion methods, and review the section.
1. Intro to Object Methods Welcome to the next section of the course! In this lesson, we begin our exploration of methods on various Ruby objects. A method is a message we can send to an object. A method produces a return value, which represents the final output of the method. |
2. Integer Methods Learn about some methods on Ruby's Integer object including next, succ, and pred. |
3. Exceptions: NoMethodError Learn about the NoMethodError exception, which Ruby raises when we invoke a method that does not exist on an object. |
4. Method Chaining Method chaining is a sequence of successive method invocations. Each invocation returns an object upon which we invoke the next method in line. |
5. The inspect Method The inspect method converts an object to a string representation for debugging. The inspect method is available on all Ruby objects. Ruby's p method invokes the inspect method on an object behind the scenes. |
6. The nil Object Learn about nil, a special Ruby object that represents nothingness, blankness, or the absence of a value. |
7. String Interpolation String interpolation is the process of injecting content into a string. That content can be anything from a variable to a Ruby expression. Within a string's double quotes, write a hashtag followed by curly braces. Write the variable or operation within the braces. |
8. The gets Method In this lesson, we'll learn about the gets method, which collects input from the user. Like puts or p, gets is a top-level method. We also discuss how to use the chomp method to chop off the newline character from the end of a string. |
9. The class Method Practice using the class method, which is available on any Ruby object and returns the class from which the object is made. The class is a blueprint for an object. Another way to think about the class is like the template or schematic. It is the abstract foundation from which a concrete object is created. We call the object an instance of a class. |
10. Methods to Convert Objects In this lesson, we'll learn how to use methods like to_i, to_f, and to_s to convert an object from one type to another (to strings, to floats, to integers, etc). |
11. Section Review [SLIDES] Review the concepts introduced in this course section including object methods, the nil object, the gets method, the class method, conversion methods, and more. |
5. Booleans and Predicate Methods
Explore Booleans, equality, inequality operators, mathematical comparisons, predicate methods, methods with arguments, and arithmetic and float methods. Conclude the section with a comprehensive review.
1. Intro to Booleans In this lesson, we'll learn about a new object type called a Boolean, which represents either true or false. |
2. The Equality Operator In this lesson, we'll explore the equality operator ( == ), which tests whether two objects are equal. |
3. The Inequality Operator In this lesson, we use the inequality operator ( != ) to test whether two objects are NOT equal. |
4. Mathematical Comparisons In this lesson, we'll learn various mathematical symbols available in Ruby including <, <=, >, and >= for greater-than/less-than logic. |
5. Predicate Methods In this lesson, we'll introduce predicate methods, which are methods that return a Boolean. These methods always end with a question mark. |
6. Methods with Arguments (include?) In this lesson, we'll learn how to pass an argument to a method. An argument is an input we pass to a method that customizes how the method will run. |
7. Methods with Multiple Arguments In this lesson, we'll practice passing multiple arguments to a method with the between? method. The between? method validates whether a number falls between a range. |
8. Arithmetic Methods In this lesson, we'll dive behind the scenes to see how Ruby translates numeric symbols like + into equivalent method calls on objects. |
9. Float Methods In this lesson, we'll learn about exclusive methods on Float objects including floor and ceil. |
10. Section Review [SLIDES] Review the concepts we've learned in this section including Booleans, predicate methods, equality and inequality operators, new object methods, and more. |
6. Methods
Combine them with the times method for code repetition, employing block variables within vertical pipes for enhanced flexibility. Learn about upto and downto methods, practicing interval-based iteration using the step method. Conclude with a thorough review of blocks, encompassing single-line and multi-line declarations, differences from arguments, and the utilization of various methods like times, upto, downto, and step.
1. Intro to Methods In this lesson, we'll introduce the syntax for declaring a method in Ruby. A method is a reusable procedure that encapsulates a piece of logic; the intent is to capture the logic once and then reuse the method throughout the program. |
2. Parameters and Arguments In this lesson, we'll cover how to define a method with a parameter and utilize the parameter in the method body. We then invoke the method and pass in sample arguments. |
3. Multiple Method Parameters In this lesson, we'll define a method with multiple parameters and pass in multiple arguments for its invocation. |
4. Manipulating Arguments Our method's arguments are regular Ruby objects so we are able to perform operations on them (such as invoking methods). In this lesson, we practice working with string and integer arguments to a custom method. |
5. Local Variables A local variable is a variable declared in a method body. Local variables only exist as long as the method executes. In this lesson, we practice declaring local variables and discuss the idea of scope, the boundary/confines within which a name exists in your program. |
6. Return Values I In this lesson, we'll learn how to declare a return value within our method. A return value is the final output of a method, the final product it creates for the outside world. Every Ruby method has a return value. |
7. Return Values II: Implicit Return Values All Ruby methods must return a value. If we do not provide a specific value, a method will return nil by default. Ruby will return the last evaluated expression as the method's return value. Thus, we can skip the return keyword and write our return value on the last line of the method. This is considered best practice in the Ruby community. |
8. Optional Parameters and Default Arguments Provide a default argument to a parameter, a fallback value to use when the invocation does not provide one. |
9. Section Review [SLIDES] In this lesson, we'll review the concepts introduced in this section of the course including: |
7. Blocks
In this section, combine them with the times method for code repetition, employing block variables within vertical pipes for enhanced flexibility. Learn about upto and downto methods, practicing interval-based iteration using the step method. Conclude with a thorough review of blocks, encompassing single-line and multi-line declarations, differences from arguments, and the utilization of various methods like times, upto, downto, and step.
1. Introduction to Blocks with the times Method Welcome to the next section of the course! In this section, we'll focus on blocks in Ruby. A block is a chunk of code that is associated with a method invocation. In this lesson, we introduce the concept in combination with the times method, which repeats a chunk of code a specified number of times. |
2. Block Variables In this lesson, we'll learn how to use vertical pipes to accept block variables in our blocks. A block variable is a dynamic value that exists only as long as the block does. It is a way for a method to pass data to the block. |
3. The upto and downto Methods In this lesson, we'll learn two more methods, upto and downto, which move from a starter integer to an end integer in steps of 1. |
4. The step Method In this lesson, we'll learn about the step, which iterates from one numeric value to another in steps/intervals. The method will enable us to practice more with blocks in Ruby. |
5. Section Review [SLIDES] In this lesson, we'll review the concepts introduced in this section of the course including: |
8. Conditionals
Combine predicate methods with if statements, grasp truthiness and falsiness, and tackle coding challenges involving if, elsif, and else in this section. Employ && and
1. The if Statement Welcome to the Conditions section of the course. In this lesson, we'll learn about the if statement, which enables us to run a section of Ruby code if a condition is met. Conditionals enable our programs to have branching logic. |
2. Predicate Methods in if Statements In this lesson, we'll learn how to combine predicate methods with if statements. The two are a perfect duo because an if statement expects a Boolean and a predicate method returns a Boolean. |
3. Truthiness and Falsiness In this lesson, we'll introduces the concepts of truthiness and falsiness. A truthy value is one that is good enough to be true in a Boolean context; a falsy value is one that is good enough to be false in a Boolean context. false and nil are the two falsy values in Ruby; all other objects/values are truthy. |
4. if and elsif In this lesson, we'll learn how add an elsif statement to check for another condition after an if. Ruby will execute the section of code belonging to the first condition that evaluates to true. |
5. if and else In this lesson, we'll introduce the else keyword, which allows us to guarantee the execution of code if no if condition or elsif condition is previously met. |
6. Multiple Conditions with And Operator (&&) In this lesson, we employ the AND operator (&&) to check for multiple conditions in an if statement. |
7. Multiple Conditions with Or Operator ( In this lesson, we continue our exploration of multiple conditions with the OR operator ( |
8. Parentheses Precedence In this lesson, we'll practice adding parentheses when using && and |
9. Nested if Statements In this lesson, we'll see how to nest an if statement inside another if statement to create a more complex logical path. All of these constructs are independent Ruby building blocks that we are free to couple together in our code. |
10. Ternary Operator In this lesson, we'll learn how to consolidate a simple if/else construct with the ternary operator. The ternary operator has a condition ? true value : false value code structure. |
11. Call A Method from Another Method In this lesson, we'll invoke one method from the body of another. This structure allows us to split up the complexity of business logic across several smaller methods. |
12. The case Statement The case statement is a shortcut that enables us to replace longwinded if/elsif/else statements with a single construct. In this lesson, we use a case statement in a method to offer a review of various food items. |
13. The unless Keyword The unless keyword creates execute if false condition for a piece of code. Ruby will execute a section of code unless a condition is met. In this lesson, we showcase the keyword alongside a classic if statement. |
14. Statement Modifiers We can replace 1-line if and unless statements with shorter statement modifiers. We put the evaluation logic in front of the respective keywords; the end keyword is not required. |
15. Conditional Assignment Operator The conditional assignment operator assigns a value to a variable if it's current value is nil. We use this design when there is an expensive computation that we only want to run once and preserve for later use in a variable. |
16. Section Review [SLIDES] In this lesson, we'll review the concepts introduced in this section of the course including: |
9. Strings I
Dive into Ruby's strings, comparing single and double quotes, and mastering multiline strings and string comparisons. Learn string concatenation, length measurement, and index-based character extraction. Explore string modification, case methods like capitalize, upcase, downcase, and the use of reverse and bang methods. Conclude with a holistic review of string functionalities.
1. Single Quotes vs Double Quotes Ruby allows us to use single quotes for string declarations. Single-quote strings do not allow string interpolation. They also do not escape characters like \n. |
2. Multiline Strings A multi-line string is officially called a here document or here doc in Ruby. Multi-line strings begin with a << symbol. Afterwards, we place an identifier that marks the start of the multi-line string. Ruby includes all content after the identifier in the string, including tabs and new lines. |
3. String Comparisons In this lesson, we review the equality (==) and inequality (!=) operators. We also introduce the < and > symbols to test whether a string comes before or after another in alphabetical order. |
4. String Concatenation Options The concat method concatenates two strings to together. Call the concat method on a string and pass it an argument of the second string We can pass only one argument (i.e. one string) to the concat method. The method mutates the original string. The prepend method is another concatenation method. It prepends (the opposite of appends) the argument to the beginning of the string |
5. The length and size Methods The length method returns the number of characters in the string. Spaces count! The size method is identical to the length method. |
6. Intro to Index Positions Ruby assigns an index position to every character in a string. The index starts counting from 0. Pass the index position within square brackets to extract a single character. Ruby returns nil if the index position does not exist. |
7. Extract Multiple Characters from a String Use square brackets to extract multiple characters from a string. |
8. Overwrite Characters in String Ruby strings are mutable. We can add, remove, or update characters. Reference the character by index position, then use = to assign a new value. |
9. The insert Method The insert method mutates a string by adding a character at a specified index position. |
10. The empty? and nil? Methods The empty? method returns true if the string is empty. Remember, a space counts as a valid character. |
11. Case Methods The capitalize method returns a new string with an uppercase first letter. The upcase method returns a string with all letters in uppercase. The downcase method returns a string with all letters downcased. |
12. The reverse Method The reverse method reverses a string's character |
13. Bang Methods on Strings Bang methods in Ruby, denoted with an exclamation point (!), modify the original object directly, offering a mutational alternative to reassigning method call return values. |
14. Section Review [SLIDES] Review the concepts introduced in this course section including: |
10. Loops
Master Ruby's loop constructs, starting with while and until loops, and tackle the FizzBuzz challenge. Learn to control loops with next and break keywords, and explore recursive methods. End with a comprehensive review of loop types, loop control mechanics, and practical applications in coding challenges.
1. The while Loop A while loop repeats a piece of condition while a condition is met. The loop rechecks the condition before each round. In this lesson, we learn the syntax for declaring a while loop in Ruby. |
2. The until Loop A while loop executes while a condition is true. An until loop executes until a condition is true. It essentially executes as long as the evalution condition is false. |
3. FizzBuzz Problem Tackle FizzBuzz, a popular coding challenge for beginners. FizzBuzz prints different conditional statements if a number is divisible by 3, 5, or both values. |
4. FizzBuzz Solution Walk through a sample solution of the FizzBuzz problem from the previous lesson. |
5. The next Keyword In this lesson, we'll introduce the next keyword, which moves execution automatically to the next iteration of a loop. In other words, it finalizes the current iteration and restarts from the beginning of the loop. |
6. The break keyword The break keyword forces the termination of a loop before its natural conclusion. |
7. Recursion I Recursion is when a method calls itself. Recursions requires us to think in multiple levels/layers of execution. |
8. Recursion II In this lesson, we practice recursion by implementing both an iterative and recursive solution for reversing a string. |
9. Section Review [SLIDES] Review the concepts introduced int he last section of the course including: |
11. Debugging
This section introduces essential debugging techniques in Ruby. Learn how to use the debug library's debugger and binding.break methods to set breakpoints, navigate through code with the step keyword, and list all variables with info. These powerful tools enhance your ability to inspect and fix issues in your Ruby programs.
1. The debugger and binding.break Methods Import the debug library with the require keyword and utilize its debugger or binding.break methods to establish breakpoints in a Ruby program. When the file runs, Ruby will pause execution at the breakpoint. We can use the continue keyword or the letter c to proceed to the next breakpoint. |
2. The step Keyword The step keyword enables us to progress through our code line by line. This can be helpful for debugging a specific section of our code. We can combine step with continue as well as techniques like outputting the values of variables in our program. |
3. The info Keyword The info keyword lists the values of all names in the program including variables and parameters. In this lesson, we combine info as well as other techniques to review the recursive reverse method from earlier in the course. |
4. Section Review [SLIDES] Review the concepts introduced in this course section including: the debug library, the continue and c keywords, the step and s keywords, the info and i keywords |
12. Arrays I: Creation and Access
Dive into the basics of arrays in Ruby, starting with their creation and understanding nested structures. Learn various methods for array creation, accessing and modifying elements by index, and handling multiple elements using different methods. Explore array comparison with operators, adding elements with push and insert, and removing elements using pop, shift, and unshift.
1. Introduction to Arrays In this lesson, we'll introduce the Array, an object for storing elements in order. |
2. Nested Arrays Nest arrays within other arrays to create multidimensional data structures. This can be helpful for modeling real world ideas like spreadsheet data. |
3. Shorthand %w Syntax to Create An Array of Strings Utilize the %w syntax to easily generate an array of strings. |
4. Access and Overwrite Array Element by Index Position Use square bracket syntax to select an element from an array. |
5. Access Single Array Element with the fetch Method Call the fetch method on an array to extract an element by index position. We can provide a fallback value as the second argument in case the index position does not exist within the array. |
6. Access and Overwrite Multiple Array Elements with Bracket Syntax Extract multiple array elements with square bracket syntax |
7. Access Multiple Array Elements with the values_at Method Use the values_at method on an array to extract non-sequential array elements. |
8. The first and last Methods Use the first and last elements on an array to return the first and last elements. Invoke the two methods with an optional numeric argument to return an array of results. |
9. The length, size, and count Methods Call the length, size, or count methods to return the number of elements in an array. |
10. The empty? and nil? Methods Use the empty? method to check if the array has no elements |
11. Equality and Inequality Operators with Arrays Use the equality (==) and inequality (!=) operators to compare two arrays |
12. The Spaceship Operator Use the spaceship operator (<=>) to compare two arrays together. |
13. The push Method and Shovel Operator Use the push method to add an element to the end of an array. |
14. The insert Method The insert method inserts or adds an element into a specific index position. It can also insert multiple values. |
15. The pop Method The pop method removes and returns an element from the end of the array. The pop method mutates the original array. No bang (!) is necessary. |
16. The shift and unshift Methods The shift method removes (and returns) an element from the beginning of the array and mutates it. So it's the inverse of the pop method. The unshift method adds an element to the beginning of the array. |
17. Section Review [SLIDES] Consolidate your knowledge of key array concepts covered in this course section, such as manipulating elements, utilizing size and capacity checks, and employing methods for adding and removing items. Also, get acquainted with comparison and position adjustment techniques among other array operations. |
13. Ranges
Explore the range object in Ruby, representing sequences of numbers or letters. Learn to create and use alphabetical ranges, check for value inclusion with include? and member? methods, and generate random numbers. Discover extracting multiple elements from strings or arrays using ranges, implement ranges in case statements, and convert ranges to arrays with the to_a method.
1. Intro to Ranges Welcome to the next section of the course. In this section, we'll explore a new object in Ruby: the range. A range represents a sequence of numbers or letters in order. We sometimes call this sequence an interval, because it represents a span of values. We can use a range to represent, for example, all the numbers between 3 and 7 or all the letters between "d" and "r". |
2. Alphabetical Ranges In this lesson, we'll learn about alphabetical ranges. An alphabetical range includes all the alphabetic characters from a starting character to an ending character. The same rules of inclusivity and exclusivity apply. Two dots means the final character is included, three dots means the final character is excluded. |
3. The include? and member? Method on Ranges In this lesson, we'll learn a few strategies to check whether or not a value exists within in a range. The first option is the include? method, which checks for inclusion on ranges. You may recall this method because it also exists on strings and arrays. The member? method is another option; it's an alias for the include? method. The === sign works as well. |
4. Random Numbers in Ruby (rand Method) In this lesson, we'll introduce the built-in rand method, which generates a random floating point number between 0 and 1. We'll see how we can utilize it with ranges in the next lesson. By default, rand returns a floating point number between 0 and 1. |
5. Extract Multiple Characters or Elements In this lesson, we'll learn how to extract a sequence of values from a string or an array using a Range. We can pass a Range object when using either square brackets or the slice method to extract multiple sequential characters. If the Range extends past the end of the array, the array will include as many elements as possible. Negative values can be used. |
6. The case Statement with Ranges In this lesson, we'll learn how to use the case statement in combination with ranges. |
7. Convert Ranges to Arrays with to_a Method In this lesson, we'll learn the to_a method to convert a range to arrays. This is helpful for generating an array of numbers or characters in sequence. |
8. Section Review [SLIDES] Recap this section's key topics, covering numeric and alphabetical ranges, utilizing 'include?' and 'member?' methods, generating random numbers using 'rand', mastering the 'case' statement, among other concepts. |
14. Arrays II: Iteration and Various Methods
Explore Ruby's advanced array methods, including iteration with each, for, and each_with_index, and alternative loops like while and until. Learn array transformation via map and collect, element selection or rejection, and array partitioning. Understand element evaluation with any? and all?, locating elements with find, detect, index, and find_index, and checking inclusion with include?. Discover how to work with maximum and minimum values and manage unlimited arguments using the splat operator.
1. The each Method Iterate over an array's elements in sequence with the each method. Pass a block to the each method to define a block variable representing each element being iterated over. |
2. Filtering with the each Method Build up a new array consisting of a subset of elements from an original array. Apply a condition using an if statement to filter down an array of elements. |
3. each within each In this lesson, we nest an each method call within the block of another each method call. We see how this can prove helpful in generating all possible combinations between two arrays. |
4. The for Loop In this lesson, we'll utilize the for loop to iterate over an array. The each method remains preferred by the Ruby community but you may encounter the more traditional for loop from time to time. |
5. The each_with_index Method In this lesson, we'll learn the each_with_index method, which iterate over an array while keeping track of the index position. |
6. Iteration over Array with while or until Loops In this lesson, we'll learn how to use the while and until loops as an alternative approach to iterate over an array's elements. |
7. The map and collect Methods In this lesson, we use the map and collect methods to iterate over an array, apply an operation to each element, and return a new array of the results. |
8. The select and reject Methods In this lesson, we explore the select and reject methods to build up a subset of an original array based on a condition being met. |
9. The partition Method In this lesson, we learn the helpful partition method, which splits an array's elements into two arrays/buckets. The first array holds the elements that satisfy a condition; the second array holds the elements that do not the satisfy the condition. |
10. The any? and all? Methods The any? method checks if any array element evaluates to true in the given block. |
11. The find and detect Mthods Use the find and detect methods to extract the first array elements that satisfies a condition. While the map/collect methods will return an array of all the matches, the find/detect methods will return the first element (if there is one). |
12. The index and find_index Methods Invoke the index or find_index methods on an array to return the index position of the first occurrence of an element. |
13. The include? Method Use the include? predicate method to check for the inclusion of any element within an array. |
14. The max and min Methods In this lesson, we'll learn the max and min methods to extract the largest and smallest elements from an array. If the array is empty, the methods will return nil. |
15. Unlimited Method Arguments/Splat Argument Use the sponge/splat operator (*) to permit a method to accept an unlimited number of arguments in that parameter position. |
16. Section Review [SLIDES] Review the concepts introduced in this section of the course including: |
15. Strings II
This section immerses you in Ruby's string manipulation techniques. Learn to divide strings into arrays using split, iterate over characters with chars and each_char, and combine array elements into a string with join. Master substring counting with count, locating substrings via index and rindex, and character removal with delete.
1. The split Method on a String The split method cuts a string based on the occurrences of a delimiter (the character that Ruby searches for). The method returns an array of segments from the original string. |
2. The chars and each_char Methods In this lesson, we explore different ways to iterate over a string's characters. The first option is to convert the string to an array with the split or chars method, then normally iterating over the array with the each method. Another option is the String's each_char method, which accepts a block to which it passes each sequential character. |
3. The join Method on an Array Invoke the join method on an array to merge its elements into a single string, optionally separating every two elements with a delimiter/separator. |
4. The count Method on a String The count method returns the number of occurrences of a substring in a string. |
5. The index and rindex Methods In this lesson, we'll use the index method to locate the first index position of a substring within a larger string. We'll also see how to search starting from the end of the string with the complementary rindex method. |
6. The delete Method Use the delete method to remove all occurrences of certain characters from a string. |
7. Section Review [SLIDES] Review the string methods introduced in this course section including: |
16. Object References and Copies
Explore object references in Ruby, learning how variable assignment creates additional names for objects and affects them through mutational methods. Delve into creating object copies with dup and clone, understand object immutability with freeze, and grasp the implications of passing objects to mutating methods.
1. Object References When we assign a variable to another variable, we create a second name for an existing object. Thus, mutational methods on either variable will affect the same underlying object. |
2. The dup and clone Methods The dup and clone methods create a copy of an existing object. Afterwards, mutational operations on the source object will have no effect on the copies. |
3. The freeze Method The freeze method makes an object immutable. Once we freeze an object, it will remain unchangeable for the duration of our Ruby program. When we dup a frozen object, the copy is unfrozen. When we clone a frozen object, the copy is also frozen. |
4. Passing Objects to Mutating Methods A method parameter is like a temporary variable for an existing object in our program. Thus, a method has the potential to mutate an object passed in as argument. A method cannot break the connection between a variable/name and its object assignment outside the method. |
17. Hashes I
Begin your journey with hashes, versatile key-value pair objects in Ruby. Learn to create hashes, use symbols as keys, and explore new shorthand syntaxes. Add and iterate over hash key-value pairs, manage inclusion with predicate methods, and selectively manipulate hashes with select and reject. Convert hashes to arrays and vice versa, understand hash merging, and handle default values in hash creation.
1. Intro to Hashes Welcome to the next section of the course! In these lessons, we'll introduce the hash, a object for creating associations between two values. A hash consists of key-value pairs. A key is a unique identifier for a hash. A real world example is a restaurant menu or a dictionary. |
2. Populate Hash and Extract Values from Keys Create our first hashes and use the => (hash rocket operator) to establish connections between key and values. Separate every subsequent key-value pair with a comma. |
3. Intro to Symbols The Symbol is a lightweight, immutable object that represents a name or label in a program. It's often described as a lightweight String because it does not come with as many methods. Symbols are frequently used as keys in a hash. In this lesson, we'll learn how to declare them in our program. |
4. Symbols as Hash Keys Use a symbol as a hash key, both with the traditional hash rocket syntax and the shortcut syntax introduced in Ruby 1.9. In the shortcut, we write the symbol name with the colon at the end rather than the beginning, then a space and the associated value. |
5. Ruby 3.1 Shorthand Hash Syntax Ruby 3.1 introduced a shorthand when a name in your program (such as a variable or a parameter) matches the key name in a hash. We can omit the value directly and just write the symbol name with a colon at the end within the hash. |
6. Add a New Key-Value Pair to Hash Use the square bracket syntax or the store method to add a key-value pair to a hash. Note that this approach will also overwrite an existing value if the key already exists within the hash. |
7. Iterating over a Hash Learn the various ways to iterate over a hash including: the each method to iterate over each key-value pair (two block variables), the each_key method to iterate over each key, and the each_value method to iterate over each value. We can also capture the keys or values in an array with the keys and values methods. |
8. Check for Inclusion in a Hash In this lesson, we'll learn how to check for inclusion with a hash. |
9. The select and reject Methods on a Hash Invoke the select and reject methods on a hash to extract a subset of key-value pairs in a new hash. In the block we provide, we'll have access to the key and value from each pair. |
10. Convert Hash to Array and Vice Versa We can convert a hash to an array with the to_a method. Ruby will return an array of nested arrays; each internal array will store a key and a value. We also need this type of array structure if we'd like to convert an array to a hash with the to_h method. |
11. The delete Method The delete method remove a key-value pair from a hash by its key. It also returns the value if we'd like to save it for later use. |
12. The merge Method The merge method combines two hashes into one. All key-value pairs will be represented in the returned hash. When there is a duplicate, Ruby will prefer the key-value pair from the argument hash. |
13. Create Hash with Default Value (Hash.new) We can invoke the new method directly on the Hash class as an alternative way to create the object. The argument we pass will be the default value that Ruby returns when we reference a hash key that does not exist. |
14. Reference Problems with Hash.new Ruby will reuse the argument we pass to Hash.new as the default value for a nonexistent hash key. This creates a problem because multiple hash keys will receive the same underlying (mutable) object. In this lesson, we'll learn how we can solve this problem with a special block syntax. |
15. Section Review [SLIDES] Review the concepts introduced in this course section including: Declaring hashes |
18. Arrays III: Bonus Methods
Master advanced array methods in Ruby. Learn to reverse arrays, sort elements, remove duplicates with uniq, and eliminate nil values using compact. Aggregate values with inject and reduce, flatten nested arrays, randomly sample elements, and explore array multiplication, union, subtraction, and intersection.
1. The reverse Method Use the reverse method to return a new array with the elements in reversed order. |
2. The sort Method Use the sort method to sort an array's elements in ascending order (smallest to greatest for numeric values, and alphabetically for strings) |
3. The uniq Method The uniq method removes all the duplicates from an array. A complementary bang method (!) is available to mutate the original array |
4. The compact Method The compact method removes all nil values from an an array. Ruby will keep false values. |
5. The inject and reduce Methods Invoke the inject or reduce method to iterate over an array while building up an aggregate value over each iteration. |
6. The flatten Method Use the flatten method to return a one-dimensional array of elements (no nested arrays). |
7. The sample Method The sample method extracts a random element from the array. Provide an integer argument to extract a different number of items in an array. The default argument is 1. |
8. Multiply an Array with an Asterisk Repeat the elements in an array by multiplying it with the asterisk symbol. |
9. Merge Arrays and Exclude Duplicates Create a union between two arrays that includes all items found in either (no duplicates included). |
10. Remove Array Items that Exist in Another Array Use the subtraction operator to remove array items that exist in another array. |
11. Array Intersection with the Ampersand Symbol Use the & operator to identify elements common to two or more arrays. |
12. Section Review [SLIDES] Review the concepts introduced in this section of the course including: |
19. Blocks, Procs, and Lambdas
Dive into blocks, procs, and lambdas in Ruby. Review block advantages and the use of yield for method customization. Understand block return values, use block_given? for defensive programming, and implement custom methods with block parameters. Explore procs as reusable code blocks, lambdas for method-like behaviors, and differentiate between procs and lambdas.
1. Review of Blocks In this lesson, we'll do a quick review of blocks in Ruby and some of its advantages/disadvantages. |
2. The yield Keyword Use the yield keyword within a method definition to transfer control to a block. The method pauses execution until the block completes. This design feature adds a layer of customization to the method call. |
3. Block Return Values A block can send a value back to the calling method. The benefit of this approach is that each block can be dynamic and do something different. But be careful not to use the return keyword, as it forces the original method to return as well. |
4. The block_given? Method The block_given? predicate method returns true if the method has received a block. We can use it to apply some defensive programming and enable our method to run with or without a block. |
5. Block Parameters Use the yield keyword to provide one or more arguments to a block. Utilize the familiar block variable syntax (vertical pipes) to receive our method's values within the block and use them. |
6. A Custom each Method Implement a custom each method by utilizing a while loop and yielding each array element to a block. The method allows us to extract the common/shared logic while extracting the dynamic/varying logic to the block. |
7. Procs In this lesson, you'll learn how to define a Proc, an object that behaves like a saved block. A block is disposable while a Proc is reusable. Procs have several syntactical declaration options but the most common one is Proc.new. |
8. More Proc Examples In this lesson, we'll practice more with declaring Procs and see how they can prove beneficial in isolating reusable block code. |
9. Methods with Proc Parameters In this lesson, we'll define a method that accepts a Proc parameter. We'll see how Procs enable us to customize a portion of method behavior while keeping other behavior constant. Ruby is pretty flexible -- it will enable methods that accept Procs to accept blocks (and vice versa). |
10. Intro to Lambdas Learn to declare a lambda, a nameless method that behaves almost identically a Proc. In the next lesson, we'll discuss the differences between procs and lambdas. |
11. Differences between Lambdas and Procs Learn the differences between Procs and lambdas. |
12. Section Review [SLIDES] Review the concepts introduced in this course section including: |
20. Classes I: The Basics
Embark on the basics of classes in Ruby, understanding objects and their blueprints. Create a class, instantiate objects, and learn about the new method. Manage object state with instance variables and initialize, declare instance methods, and override to_s. Discover the self keyword, getter and setter methods, and simplify attribute access with attr_reader, attr_writer, and attr_accessor. Add parameters to initialize for customized instantiation.
1. Intro to Classes Explore the foundational concepts of object-oriented programming as we discuss what constitutes an object and its blueprint, the class. Learn about instance variables that define an object's state. |
2. Create a Class Join us as we define our very first Ruby class- Guitar. We'll learn the basics of class creation and instantiate some objects to demonstrate the principles in practice. |
3. The new Method on Ruby's Native Objects Discover the 'new' method used in Ruby's native objects like Hash, String, and Array, and understand how common syntax is actually shorthand for these method calls. |
4. Instance Variables and the initialize Method Dive into instance variables, the pillars of an object's state, and learn how the 'initialize' method plays a crucial role in setting up an object upon instantiation. |
5. Instance Methods Explore how to declare instance methods within a Ruby class and understand their role in encapsulating functionality that is unique to each object instance. |
6. Override the to_s Method Learn about the to_s method inherited from the Object class, how it functions within our custom Guitar class, and how overriding it can change object output behavior. |
7. The self Keyword Unpack the concept of the self keyword in Ruby, which represents the current object context, and see how it varies across different scopes within the program. |
8. Omitting the self Keyword Understand when and why you can omit the self keyword in your Ruby code, and what implications it has for method calls and object references. |
9. Getter Methods (Read Methods) Grasp the principles of encapsulation with a deep dive into getter methods, which allow you to access an object's state while preserving its integrity. |
10. Setter Methods (Write Methods) Discover the function and syntax of setter methods in Ruby, which enable you to assign new values to an object's instance variables. |
11. The attr_reader and attr_writer Methods Accessor methods in Ruby are instance methods designed to retrieve (get) or assign (set) values to instance variables. Ruby simplifies the creation of these methods with shorthand syntax for both 'attribute readers' to retrieve values and 'attribute writers' to set them. These shortcuts offer a concise alternative to the longer code examples discussed in previous lessons. |
12. The attr_accessor Method Combine the functionality of reader and writer methods with attr_accessor, Ruby's way to define a two-way access for an instance variable. |
13. Add Parameters to initialize Method Expand the capabilities of the initialize method by adding parameters, allowing for more flexible and customized object instantiation. |
14. Section Review [SLIDES] Recap the key concepts covered in this section, from the basics of class definition to the intricacies of instance variables and methods, accessor shortcuts, and more, with a comprehensive slide review. |
21. Classes II
Explore Ruby's private and protected methods for access control within classes and subclasses. Master data validation in setter methods, dynamic attribute derivation, the differentiation between instance and class methods, and various class method syntaxes. Learn to evolve classes over time and employ monkey patching for enhanced functionality, all culminating in a detailed section review.
1. Private Methods Learn how to encapsulate the internal workings of your classes in Ruby by defining private methods. This video explains the concept of private methods and demonstrates how they can be used to prevent direct access from outside the class. |
2. Protected Methods Understand the nuances of access control in Ruby with protected methods. This video guides you through defining protected methods in a class, highlighting how they are accessible within the class and its subclasses. |
3. Add Validation to Setter Methods Discover how to safeguard your classes against invalid data. This tutorial will teach you to add validation checks to setter methods, ensuring that only appropriate values are assigned to object attributes. |
4. Derived Values This video will explain how to compute and work with derived values within a Ruby class, allowing you to create dynamic attributes based on the state of the object. |
5. Class Methods Dive into the static side of Ruby classes by defining class methods. Learn the distinction between instance methods and class methods, and how the latter can be used without instantiating objects. |
6. Alternative Class Method Syntax Explore different ways to define class methods in Ruby. This video introduces alternative syntaxes and when you might choose one style over another for better code organization. |
7. Class Variables This lesson covers the use of class variables in Ruby. Understand how to declare variables at the class level and how they differ from instance variables in terms of scope and behavior. |
8. Building a Class Over Time Gain insight into the iterative development of a Ruby class. This video will show you how a class can evolve over time as new requirements emerge and features are added. |
9. Monkey Patching Learn about the concept of monkey patching in Ruby and how it allows you to add functionality to existing classes. This video provides a practical demonstration of extending Ruby's built-in Array and String classes. |
10. Section Review [SLIDES] Wrap up the section with a detailed review of the topics covered, presented through informative slides. This summary will help reinforce your understanding of when and how to use private and protected methods, class methods, and monkey patching in Ruby. |
22. Keyword Arguments
Delve into keyword arguments in Ruby, enhancing code flexibility and clarity. Start with hash-based initialization, then learn required and optional keyword arguments, and the interplay with positional arguments. Apply these techniques to refactor a class, ending with a comprehensive review that solidifies your understanding of keyword arguments.
1. Hash as initialize Argument Discover the power of using hashes as initialization arguments in methods to enhance the flexibility of your code. This video will walk you through the process of setting up a method that accepts a hash to initialize object attributes. |
2. Required Keyword Arguments Learn how to define methods with required keyword arguments to ensure that certain keys are always passed, improving code clarity and error handling. |
3. Optional Keyword Arguments Explore the versatility of optional keyword arguments in your methods, allowing for more adaptable and scalable code. This video demonstrates how to set defaults and manage the absence of specific arguments gracefully. |
4. Positional Arguments and Keyword Arguments Understand the differences and interplay between positional arguments and keyword arguments in method definitions, and learn how to use them effectively in combination. |
5. New Version of Candidate Class with Keyword Arguments See a practical implementation of keyword arguments by refactoring the Candidate class. This video showcases how keyword arguments can simplify object initialization and make your codebase more maintainable. |
6. Section Review [SLIDES] Conclude the section with a comprehensive review of keyword arguments in Ruby. The slides will summarize key points, clarifying the best use cases and advantages of this powerful feature. |
23. Classes III: Inheritance
Embark on an exploration of inheritance in Ruby, beginning with superclasses and subclasses. Understand the hierarchy with superclass and ancestors methods, examine object type checking, exclusive instance methods, and method overriding. Learn the super keyword's applications, defining equality, and duck typing, concluding with an insightful section review.
1. Intro to Inheritance [SLIDES] Introduce inheritance, superclasses, and subclasses |
2. Create Subclasses Create a superclasses and two subclasses that inherit from it. |
3. The superclass and ancestors Class Methods Explore the intricacies of inheritance in Ruby with this video. Dive into the hierarchy that shapes object functionality, uncovering how classes like Integer, Numeric, and Object are interlinked, and learn to trace an object's lineage with superclass and ancestors methods. |
4. Check Inheritance Hierarchy of our Subclasses Use < syntax to test whether a class inherits from another. Review the .ancestors method on a class. |
5. The is_a? and instance_of? Methods Call the .is_a? method to test if an object inherits from the class passed as the argument. |
6. The methods Method In this tutorial, we'll delve into the functionality and application of the 'methods' method. |
7. Exclusive Instance Methods in Subclasses Define exclusive methods on subclasses. |
8. Override Methods in a Subclass Define a method on a subclass that overrides the same method on a superclass. |
9. The super Keyword I Use the super keyword in a subclass method to invoke the same method in the superclass. |
10. The super Keyword II Explore three different ways to use super: without parentheses |
11. Defining Equality In this lesson we will learn how to define equality for our own objects. In other words, how to define the logic that Ruby is going to use to determine if two objects made from a custom class are infact equal. |
12. Duck Typing "Duck Typing" introduces the dynamic typing methodology that is guided by the principle: "If it looks like a duck and quacks like a duck, it must be a duck." This video explains how duck typing works in programming, demonstrating how the behavior of an object determines its suitability for use, rather than its class or inheritance hierarchy. |
13. Section Review [SLIDES] We have reached the end of this section. Let's review the concepts introduced in the section. |
24. Input and Output
Engage in Ruby's file and command line operations. Learn to read and write text files using File.open, manage files with renaming and deleting, and harness command line arguments with ARGV. Discover importing Ruby files with load, require, and require_relative methods, rounding off with a review that reinforces your I/O operation skills.
1. Read from a Text File Utilize the File.open class method to read a text file into Ruby. Iterate over the file's contents line-by-line with the each method on the resulting File object. |
2. Write to a Text File Call the File.open class method with an optional w argument to enable Ruby to write content to the file. Utilize the file.puts method to add a line to the file and file.write to add a line without a line break. |
3. Rename and Delete a File Invoke the File.rename and File.delete class methods to rename and delete a file on your hard drive. Use the File.exists? predicate method to check for the existence of a file before performing an operation. |
4. Command Line Arguments (ARGV) Pass in arguments to a Ruby program through the Command Line. Use the ARGV array to capture and interact with the command line arguments. All arguments will arrive as strings in the program. |
5. Load A Ruby File with load Method The load runs another Ruby file in the present Ruby file. The process registers names like methods and classes, making them available to use within the program. load will run as many times as it is used. |
6. The require and require_relative Methods Call the require and require_relative methods to import another Ruby file into the current program. Unlike load, require will cache the original import and not re-read the same file twice. The require method looks for the specified file in the Ruby installation directory; we can tell it look in the current folder with ./ before the file name. A more popular alternative is the require_relative method, which starts looking for the file in the current directory. |
7. Section Review [SLIDES] Review the concepts introduced in this course section including: |
25. Modules and Mixins
Explore and master Ruby's Modules and Mixins, covering creation, integration, and practical applications, including built-in functionalities and custom enhancements in this section.
1. Intro to Modules Define a module with a constant and three methods. |
2. Modules with Identical Methods Define multiple modules with identically named methods. |
3. Import Modules into the Current File Review the require method to import a Ruby file into the present one. |
4. The Math Module Call methods from Ruby's built in Math module. |
5. The uri and net/http Modules Import the uri and net/http files to gain access to the URI and Net modules. We then utilize module methods and classes to make a web request to Google.com. |
6. The Enumerable Mixin Introduce the concept of mixins, a module whose methods we add to a class definition. Use the built-in Enumerable module to mixin 50 methods related to iteration. |
7. The Comparable Mixin Explore Ruby's built in Comparable module, which is mixed into various classes to add compare functionality. Mix in the module into a new OlympicMedal class to allow comparisons. |
8. Mixing in Our Own Module Define our own custom Purchaseable module with a method. Mix the module into multiple classes, including a superclass. |
9. The ancestors Method in Depth Review the ancestors class method, which returns the complete inheritance hierarchy of a class. Review the order in which Ruby looks for a method among superclasses and mixins. |
10. The prepend Keyword The prepend keyword operates similarly to include but ensure's that the module's methods take precedence over similarly-named methods defined in the class. |
11. The extend Keyword The extend keyword adds a module's methods to the class as class methods |
12. Mixing in Multiple Modules We can mix multiple modules into the same class with successive uses of the include keyword. When there are name collisions, Ruby will prioritize the method in the last module that was mixed in. |
13. Multiple Declarations for the Same Module One common pattern is declaring the same module across multiple rules. Ruby builds up/aggregates the composite module based on all the code it parses. |
14. Modules within Modules We can nest methods, classes, constants, even other modules within a Ruby module. In this lesson, we show how this can be advantageous in organizing related code. |
15. Section Review [SLIDES] Review all the concepts introduced in the previous course section including: |
26. Sets
Discover Ruby's Set class, a distinct object type that maintains unique, unordered elements. This section delves into fundamental operations such as adding and removing items, alongside an exploration of the Set class's source code on GitHub. Conclude with a thorough review and exercise solutions, reinforcing your grasp on sets in Ruby.
1. Intro to Sets In this section, we'll learn about another Ruby object called a set. A Set is a mutable, unordered data structure that guarantees the uniqueness of its elements. |
2. Add and Delete Items from Set In this lesson, we learn the add and delete methods for adding and removing elements from a Set. We explore how these methods operate when their argument exists and doesn't exist within the Set. |
3. Explore set.rb on GitHub In this lesson, we explore the Set class's source code on GitHub. |
4. Section Review [SLIDES] Review all the concepts introduced in the previous section of the course. |
27. Datetimes
Navigate the world of Ruby's Date and Time objects, learning to handle and manipulate dates, times, and time zones. Explore methods for date-time operations, including arithmetic and comparisons, and techniques to format and parse time strings. The section rounds off with an extensive review and coding exercise solutions, deepening your understanding of Ruby's datetime handling.
1. The Date Object The Date object represents a date (year, month, day). In this lesson, we practice instantiating a few Date objects and see what Ruby does when we do not provide specific pieces of data. |
2. The Time Object The Time object represents a datetime (a day, a time, and a timezone). It is the newer version of the deprecated DateTime class. We can invoke the new and now class methods to create a Time representing the current time. We can also provide new with the year, month, day, hours, minutes, and second. |
3. Add or Subtract Time We can use addition and subtraction operators to add and subtract time. Ruby will return a new Time object. Duration must be expressed in seconds. For example, adding 60 to a Time means adding 60 seconds or 1 minute. |
4. The Comparable Methods on a Time Object The Comparable modules adds methods for comparison. The Ruby team mixes in the module to the Time class. We can thus perform comparison operations like equality, inequality, less than, greater than, between?, and more between two Time objects. |
5. Convert Time Object to Formatted String The strftime (string format time) method converts a Time object to a string. Its string argument customizes how the string will look. We can customize the included pieces of information, the separators (i.e., slashes or spaces), and their order. |
6. The parse and strptime Methods The parse and strptime (string parse time) method convert a string into a valid Time object. The strptime method is more reliable but requires additional syntax to designate the format that the time string holds. |
7. Section Review [SLIDES] Review the concepts introduced in this course section including: |
28. Regular Expressions
Embark on mastering Ruby's regular expressions for effective text search and pattern matching. Starting with basic Regexp objects and search methods, progress to advanced techniques using various symbols for pattern matching and text manipulation methods like sub and gsub. Practice your skills on Rubular.com and solidify your knowledge with a comprehensive section review, including coding challenge solutions.
1. Intro to Regular Expressions A regular expression is a search pattern for text. In this lesson, we review some of Ruby's simple search methods like include?, start_with, and end_with?. We then practice instantiating our first Regexp objects using the // syntax. |
2. The scan Method The scan method returns an array of all matches of the regular expression in a search string. In this lesson, we practice searching for one and multiple characters in a sample piece of text. |
3. The Digit Symbol In this lesson, we learn the \d symbol to designate a digit in a regular expression. We also learn special symbols to customize the pattern such as + for one or more in a row and {n} for an exact number of that character in a row. |
4. The Wildcard Symbol Use the period (.) to represent any character in a regular expression. This character is particularly powerful when combining it with other search characters. |
5. Anchors Utilize the \A and \z RegEx symbols to search for patterns at the start or end of a string. |
6. Exclude Characters Combine square brackets with the caret symbol (^) to exclude characters from a RegEx search. |
7. The sub and gsub Methods with Regular Expressions Use the sub and gsub methods to find and replace either the first occurrence or all occurrences of a RegEx match in a string. |
8. Rubular.com Navigate to Rubular.com, a popular resource for experimenting with Ruby regular expressions in your browser. |
9. Section Review [SLIDES] Review the concepts introduced in this course section including: |
29. Exceptions
Discover how to handle errors and exceptions in Ruby. Learn to use begin and rescue for error-prone code, capture exceptions with => e, and utilize retry for retrying code execution. Understand the importance of ensure for executing code regardless of exceptions, and how to manually raise exceptions with raise. Delve into creating custom error classes and review the section with an exercise solution and a comprehensive slide review covering Ruby's built-in exceptions, custom error classes, and key keywords for exception handling.
1. The begin and rescue Keywords Use the begin keyword to define a section of Ruby code with the potential of error. Use the rescue keyword to rescue any error/exception and react to it. |
2. Catching Error Object We can capture the error object that Ruby generates during an exception with the => e syntax (the name is up to you). It is advantageous to write multiple rescue clauses if we need to react differently to different error types. |
3. The retry Keyword The retry keyword retries the code that caused an error by running the begin block again. Watch out for infinite loops - your rescue section must fix the original problem to ensure the begin section executes without issue the second time it runs. |
4. The ensure Keyword The ensure keyword defines a section of code that will always run (whether the begin section executes successfully or triggers an exception). We typically use it to perform clean-up code (closing files, terminating connections, etc). |
5. Using begin and rescue at Top Level There are 2 alternative ways we can use begin and rescue: |
6. The raise Keyword The raise keyword forces Ruby to raise an exception. We use it to manually force an error and mode real-world issues. Ruby only hows to identify its own technical, language-related problems; with raise, we ask Ruby to trust us in identifying a potential logical problem in our code. |
7. Custom Exceptions In this lesson, we define a custom error class that inherits from the StandardError class. We also discuss Ruby's inheritance hierachy and rescue an error from our own custom class. |
8. Section Review [SLIDES] Review the concepts introduced in this section of the course including: |
30. Testing with Minitest
Immerse yourself in testing Ruby code using Minitest. Start with basic testing concepts and assertions, then test a simple class for practical understanding. Learn to set up and tear down test environments with setup and teardown methods. Practice assertions like assert_includes and assert_raises to validate element inclusion and exception handling. Enhance your testing messages with custom strings in assertions. The section concludes with a review of Minitest features, class inheritance, common assertions, and setup/teardown methods.
1. Intro to Testing Import the minitest/autorun module, declare a test class that inherits from Minitest::Test, and practice using common assertions like assert_equal to validate our code. |
2. Testing a Class Practice some more with the Minitest syntax including requiring the minitest/autorun file, defining a test class, and using built-in assertions like assert_equal. In this lesson, we write tests for a simple Pokemon class. |
3. The setup and teardown Methods Use the setup method within a Minitest::Test class to run code before each test method. The teardown method runs code after each test method. To access data from setup within a test method, we need to assign values to instance variables. |
4. Assert Inclusion The assert_includes assertion validates that something exists within something else (such as an element within an array). In this lesson, we expand our Pokemon class to support an array of attacks; we then use assert_includes to check for the presence of a string within it. |
5. Assert Error was Raised The assert_raises method validates that a specified chunk of code raised a specific exception. We pass an argument of the exception as well as the block with the code for Minitest to execute (which should trigger that error). |
6. Final Argument to Assertion Methods You can provide a string as the final optional argument to an assertion method to customize the message that appears when the assertion is not met. In this lesson, we practice this syntax with our assert_equal, assert_includes, and assert_raises methods. |
7. Section Review [SLIDES] Review the concepts introduced in this section of the course including: |
31. Reading and Writing Documentation
Gain proficiency in navigating and understanding Ruby's official documentation. Learn to differentiate between class and instance methods in documentation using :: and #. Explore generating webpage documentation for Ruby projects using RDoc, enhancing your ability to annotate and understand code in Ruby projects.
1. Reading Documentation Navigate to the official Ruby documentation and use it to search for classes and methods. The docs use :: to designate class methods and # to designate instance methods. |
2. Use RDoc to Generate Documentation Use the rdoc command-line to generate webpage documentation for a Ruby project. We use regular comments in our code to annotate the code. |
32. Gems
Explore the world of Ruby Gems, understanding how to enhance your projects with pre-written code bundles. Learn how to update the gem program, install gems using gem install and bundle install, and manage project dependencies through a Gemfile. Practice using the Faker Gem to generate random data, showcasing the practical integration of gems into Ruby projects.
1. Intro to Ruby Gems Take a tour of RubyGems, an online server of 175,000 Ruby Gems that we can add to our projects. A Gem is a bundle of code written by other developers. |
2. Updating Gem Program In this lesson, we update the gem program that is installed alongside Ruby. Updating to the latest version is helpful to get bug fixes and performance optimizations. |
3. Installing Faker Gem In this lesson, we practice installing Gems with both the gem install and bundle install commands. The bundle install command looks for a Gemfile in your project. A Gemfile lists the project's dependencies (i.e. Gems) and ensures that all developers are working with the same version of the Gems. |
4. Use Faker Gem Use the Faker Gem to generate random names, instruments, football players, and more. The goal here is to see how we incorporate a sample Gem's code into our own Ruby project. |
33. Conclusion
Celebrate the completion of the course! This final session wraps up the journey, summarizing key learnings and achievements throughout the course. Reflect on the skills acquired and how they can be applied to future Ruby programming endeavors.
1. Conclusion Celebrate finishing the course! Let's wrap up in this session. |