Comprehensive Ruby Programming
()
About this ebook
- Provides the core skills required to become a Ruby programmer
- Covers how to use the most popular Ruby Gem libraries
- Includes details on regular expressions
This is a complete course written from the ground up for beginners wanting to gain a solid understanding of the Ruby language. It starts at the beginning with how to install Ruby and work with it on multiple machines, so simply have a computer that's connected to the Internet and you'll be ready.
Related to Comprehensive Ruby Programming
Related ebooks
Svelte and Sapper in Action Rating: 2 out of 5 stars2/5The Way to Go: A Thorough Introduction to the Go Programming Language Rating: 2 out of 5 stars2/5Learning Concurrent Programming in Scala - Second Edition Rating: 0 out of 5 stars0 ratingsGo Cookbook Rating: 5 out of 5 stars5/5RSpec Essentials Rating: 3 out of 5 stars3/5JavaScript Regular Expressions Rating: 3 out of 5 stars3/5Swift Functional Programming - Second Edition Rating: 3 out of 5 stars3/5Clean Code in JavaScript: Develop reliable, maintainable, and robust JavaScript Rating: 5 out of 5 stars5/5Programming Kotlin Rating: 0 out of 5 stars0 ratingsJavaScript Unlocked Rating: 5 out of 5 stars5/5Node.js By Example Rating: 2 out of 5 stars2/5Scala Design Patterns Rating: 0 out of 5 stars0 ratingsReactive Programming for .NET Developers Rating: 0 out of 5 stars0 ratingsReact Projects: Build 12 real-world applications from scratch using React, React Native, and React 360 Rating: 0 out of 5 stars0 ratingsGo Design Patterns Rating: 5 out of 5 stars5/5JavaScript Projects for Kids Rating: 0 out of 5 stars0 ratingsMastering Java EE Development with WildFly Rating: 0 out of 5 stars0 ratingsRUBY Beginner's Crash Course: Ruby for Beginner's Guide to Ruby Programming, Ruby On Rails & Rails Programming Rating: 0 out of 5 stars0 ratingsTypeScript Design Patterns Rating: 0 out of 5 stars0 ratingsReact Design Patterns and Best Practices Rating: 0 out of 5 stars0 ratingsDjango Design Patterns and Best Practices Rating: 5 out of 5 stars5/5Mastering JavaScript Design Patterns - Second Edition Rating: 5 out of 5 stars5/5Modular Programming with PHP 7 Rating: 0 out of 5 stars0 ratingsGo Programming Blueprints Rating: 0 out of 5 stars0 ratingsTest-Driven Java Development Rating: 4 out of 5 stars4/5Introduction to JVM Languages Rating: 0 out of 5 stars0 ratingsLearning Dart Rating: 0 out of 5 stars0 ratingsGetting Started with React Rating: 0 out of 5 stars0 ratingsLearning Go Programming Rating: 5 out of 5 stars5/5
Programming For You
Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Java for Beginners: A Crash Course to Learn Java Programming in 1 Week Rating: 5 out of 5 stars5/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5HTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5SQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Learn SQL in 24 Hours Rating: 5 out of 5 stars5/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Learn JavaScript in 24 Hours Rating: 3 out of 5 stars3/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Python Machine Learning By Example Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5TensorFlow in 1 Day: Make your own Neural Network Rating: 4 out of 5 stars4/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Photoshop For Beginners: Learn Adobe Photoshop cs5 Basics With Tutorials Rating: 0 out of 5 stars0 ratingsModern C++ for Absolute Beginners: A Friendly Introduction to C++ Programming Language and C++11 to C++20 Standards Rating: 0 out of 5 stars0 ratingsPython QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsHTML in 30 Pages Rating: 5 out of 5 stars5/5Programming Arduino: Getting Started with Sketches Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Mastering Windows PowerShell Scripting Rating: 4 out of 5 stars4/5Python Essentials Rating: 5 out of 5 stars5/5
Reviews for Comprehensive Ruby Programming
0 ratings0 reviews
Book preview
Comprehensive Ruby Programming - Jordan Hudgens
Comprehensive Ruby Programming
Go from beginner to confident programmer
Jordan Hudgens
BIRMINGHAM - MUMBAI
Comprehensive Ruby Programming
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: June 2017
Production reference: 1280617
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78728-064-9
Credits
About the Author
Jordan Hudgens is the CTO and founder of DevCamp, where he leads instruction and curriculum development for all the DevCamp and Bottega code schools around the US.
As a developer over the past decade, Jordan has traveled the world building applications and training individuals on a wide variety of topics, including Ruby development, big data analysis, and software engineering.
Jordan focuses on project-driven education as opposed to theory-based development. This style of teaching is conducive to learning how to build real-world products that adhere to industry best practices.
Additionally, Jordan has published multiple books on programming and computer science along with developing training curriculum for Learn.co, DevCamp, and AppDev on the topics, namely Ruby on Rails, Java, AngularJS, NoSQL, API development, and algorithms.
www.PacktPub.com
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Customer Feedback
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787280640.
If you'd like to join our team of regular reviewers, you can e-mail us at customerreviews@packtpub.com. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Table of Contents
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Introduction to the Ruby Programming Language
What is Ruby?
Popular sites that use Ruby
Installing Ruby on a computer
Ruby language dashboard
Installing different Ruby versions with RVM
Summary
Ruby Variables
Using variables in Ruby
Variable code implementation
Printing to the Ruby console
Using puts
Using p
Getting input from the Ruby console using gets and chomp
Code implementation
Variable scope and variable types
Local variables
Global variables
Instance variables
Constants
Class variables
Summary
Ruby Strings
Using strings in Ruby
Missing quotation marks
Printing strings
Storing strings in variables
String interpolation guide for Ruby
What is string interpolation?
String manipulation guide
What is string manipulation?
String manipulation code examples
Method chaining
A practical implementation
Give it a bang!
String substitution guide
Adding a bang
Becoming a block head
Split, strip, and join guides for strings
Using the strip method
Using the split method
Using the join method
Summary
Working with Numbers in Ruby
Integer arithmetic guide
Arithmetic order of operations
Difference between integers and floats
Summary
Ruby Methods
Creating methods in Ruby
What does a Ruby method return?
What are the differences between class and instance methods in Ruby?
Ruby proc tutorial
Proc code example
What is a block?
The Ruby lambda tutorial
Stabby lambdas
What is the difference between procs and lambdas in Ruby?
Argument count
Return behavior
Guide to method arguments in Ruby
What are method arguments?
Method argument syntax
Method argument code examples
Named arguments
Default argument values
Using splat and optional arguments in Ruby methods
Traditional splat arguments
Keyword-based splat arguments
Optional arguments
Summary
Ruby Iterators and Loops
The while loop guide
The while loop code example
The each iterator method tutorial
The each loop code example
The for...in loops tutorial
Looping over a hash
Nested iterator code example
Using the select method
Using the map method – part 1
The map method code example
Using the map method – part 2
Summing values in an array using the inject method
Summary
Ruby Collections
Using arrays
Deleting items from arrays
Using push and pop for arrays
The Ruby hash tutorial
The hash code example
Deleting elements from a hash
Iterating over a hash for a key or value
Top hash methods in Ruby
Adding elements to a hash
Swapping keys and values
Merging hashes
Converting a hash into an array
Listing all keys
Listing all values
Summary
Ruby Conditionals
The conditionals guide
Real-world use of conditionals
Code example of conditionals
Syntax for the unless conditional
Running Ruby files
The unless conditional code example
Nested if...else conditionals
The if...elsif conditional code example
The conditional workflow
Guide to compound conditionals
Compound conditionals code example
Compounded compound conditionals
Additional conditional operators
Summary
Object-Oriented Programming in Ruby
Introduction to how OOP works
A real-world OOP example
Ruby OOP development – setters, getters, and methods
Working with instantiation in Ruby
What does instantiation mean? – A real-world example
Connecting the dots
Instantiation code example
Implementing instantiation
Creating an initializer method in a Ruby class
Adding an initializer to a Ruby class
Working with optional values
Using named arguments
Overriding default values
The working of OOP inheritance
Overview of private versus public methods
Private versus public methods
Private method code example
The working of polymorphism and usage of super
So how does polymorphism fit in?
Dead simple OOP
My history with OOP
How does OOP work?
SOLID OOP development – the simple responsibility principle
The single responsibility principle
The SRP in the real world
An SRP example
The class that knew too much
Rule of thumb – no ands allowed
A mailer class
The sales tax class
Why the SRP is important
SOLID OOP development – the open/closed principle guide and example
The open/closed principle definition
A surprisingly challenging task
The open/closed principle example
The naive approach
I don't like change!
A better way
SOLID OOP development – the Liskov substitution principle
The LSP definition
Breaking down the LSP
The LSP example
The problem
The LSP violation
The fix
SOLID OOP development – the interface segregation principle
The ISP definition
The ISP code example
Introducing the moderator
A better way
The result
A caveat
SOLID OOP development – the dependency inversion principle
The DIP in the real world
The DIP definition
The DIP code example
Recap
Summary
Working with the Filesystem in Ruby
Creating a file
Ruby File class
Other options you can pass as the second option
Reading files into a program using the File class
Deleting a file
Appending a file
Building a log file
Summary
Error Handling in Ruby
Error handling tutorial
Error handling – the best practices
Developing a custom error logger in Ruby
Summary
Regular Expressions in Ruby
Regular expression code example
Regex code example
How to validate an IP address using regular expressions
How to develop a wheel of fortune game
Summary
Searching with grep in Ruby
How to use grep in Ruby
How to use grep instead of the select and map methods
Summary
Ruby Gems
Introduction to Ruby gems
How to research Ruby gems
How to research gems
Summary
Ruby Metaprogramming
Metaprogramming introduction
How to integrate metaprogramming techniques into a custom class
How to use metaprogramming for opening and customizing the String class
How Rails use metaprogramming for the find_by method
Utilizing metaprogramming with method_missing to create methods on the fly
Why do we need to call super?
Resources
Incorporating respond_to_missing to conform to metaprogramming best practices
Resources
Implementing metaprogramming with define_method
Resources
Summary
Ruby Web Frameworks
Sinatra web framework development
Introduction to the Ruby on Rails framework
Summary
Working with APIs in Ruby
How to work with APIs in Ruby
How to use the httparty Ruby gem
How to create a custom API connector in Ruby
How to parse an API in Ruby
Summary
Ruby Algorithms
Introduction to sorting algorithms
Bubble sort
Quick sort
Merge sort
Implementing the bubble sort algorithm
Bubble sort code example
Implementing the quick sort algorithm
Explanation of quick sort
code example
Implementing the merge sort algorithm
Implementing a prime number counting algorithm
How to code the power digit sum algorithm
Implementing a humanize counting algorithm
Implementing a date algorithm
How to code a Fibonacci digit counter
Implementing a permutation algorithm
Implementing an amicable number algorithm
Implementing a factorial algorithm
Implementing an even Fibonacci number algorithm
Implementing the least common multiple
Summary
Machine Learning
Big data analysis
Basic decision tree implementation
Addition of attributes
Addition of training data and its values
Calling the ID3 method
Function of the train method
Addition of the test method
Setting up decision variables
Print the results out
Testing the program
Advantage of decision trees over if...else statements
How to develop a big data analysis application in Ruby
Summary
Preface
Coding has become one of the most critical skills you can have for furthering your career. Whether you are an experienced developer who wants to learn a new language or you are new to programming, this course can be your comprehensive Ruby coding guide. Starting with foundational principles, such as syntax and scaling up, to advanced topics, such as metaprogramming and big data analysis, I wanted to create a curriculum that will give you all the tools you need to be a professional Ruby developer. With over a decade of real-world development experience, I have engineered this book to ensure it focuses on the skills you will need to be a professional Ruby developer.
What this book covers
Chapter 1, Introduction to the Ruby Programming Language, gives a high-level view of the Ruby programming language, how to install it on your system, and getting it up and running so you can start building Ruby programs.
Chapter 2, Ruby Variables, teaches you how to work with variables in Ruby to store data and use the data throughout a program, because Ruby variables are the building blocks of just about every Ruby program.
Chapter 3, Ruby Strings, teaches about the Ruby string data type and walks you through how to integrate string data into a Ruby program. Working with words, sentences, and paragraphs are common requirements in many applications.
Chapter 4, Working with Numbers in Ruby, explains how to work with different number data types in a Ruby program, including the integer and float types. A key component in building programs is developing mathematical equations in order to implement various algorithms.
Chapter 5, Ruby Methods, teaches how to create and use methods in Ruby programs to store processes and reuse them throughout a program, including an overview of procs and lambdas. One of the most powerful tools available to developers is the ability to store functionality and share that behavior throughout a program.
Chapter 6, Ruby Iterators and Loops, works you through the powerful iteration tools that come with the Ruby programming language that allow you to traverse various collection types. When it comes to developing programs, one of the common tools utilized by programmers is the ability to loop through collections of data.
Chapter 7, Ruby Collections, shows that nearly every application that you will build will need to implement collections of data in some form or another. This could be anything from a database query that returns multiple records to a set of dates in a calendar.
Chapter 8, Ruby Conditionals, teaches how to integrate conditionals into a Ruby program, which will enable your programs to have dynamic behavior based on different input data. A key component for building dynamic behavior into Ruby applications requires conditional logic at some stage or another.
Chapter 9, Object-Oriented Programming in Ruby, teaches you Object-Oriented Programming (OOP) for Ruby, including creating classes, instantiating objects, working with inheritance, and polymorphism. In addition to readability, one of the defining attributes of the Ruby programming language is how it implements OOP techniques.
Chapter 10, Working with the Filesystem in Ruby, reveals various ways to work with files in Ruby, including the ability to create, open, edit, and delete files using built-in methods and classes.
Chapter 11, Error Handling in Ruby, explains how to work with errors in Ruby, including how to build practical tools such as an error logging program. Many new developers are intimidated when they come across errors and exceptions in a program. However, errors are Ruby's way of telling you how you can improve or alter your program to work properly.
Chapter 12, Regular Expressions in Ruby, enables you to work with regular expressions in Ruby, including the built in Regex class that allows you to build matchers and dynamically search through data. Pattern matching is a common requirement for building code libraries such as validations and basic search functionality.
Chapter 13, Searching with grep in Ruby, teaches how to use the powerful grep method in Ruby programs in order to search through data. Ruby offers a wide variety of options when it comes to searching through strings.
Chapter 14, Ruby Gems, walks you through and teaches what Ruby gems are, how to use them, and where you can find new gems to give your Ruby programs additional functionality. One of the reasons for Ruby's growth in popularity over the past decade is the open source community building code libraries that can be implemented in other applications. Typically, these code libraries are called Ruby gems.
Chapter 15, Ruby Metaprogramming, explains some of the basics of metaprogramming in Ruby, including how to open classes and add functionality to built-in Ruby classes. Writing code that writes code is one of the more challenging topics in any programming language. However, metaprogramming in Ruby offers such a powerful interface for building advanced features into an application. It is worth the effort to learn it.
Chapter 16, Ruby Web Frameworks, reveals the two most popular web frameworks for Ruby programs, Rails and Sinatra, including building applications for both frameworks.
Chapter 17, Working with APIs in Ruby, walks you through how to work with APIs and build a Ruby program that communicates with a third-party API and parses the JSON data. Working with outside services is a powerful mechanism for building data-driven applications.
Chapter 18, Ruby Algorithms, puts together all of the knowledge that we've compiled in the book in order to implement popular algorithms. Specifically, you'll learn how to build advanced algorithms in the Ruby programming language, including the sorting methods, such as quick sort and merge sort, along with a number of functional programming algorithms.
Chapter 19, Machine Learning, teaches how to integrate machine learning algorithms into a Ruby program, including how to build a decision tree, train it, and have it output dynamic results. One of the fastest growing sectors in development is machine learning.
What you need for this book
This course starts at the beginning with how to install Ruby and work with it on multiple machines, so simply have a computer that's connected to the internet and you'll be ready. I'll also show how to run Ruby programs in the browser, so you can work through this book on any operating system.
Who this book is for
This is a complete course written from the ground up for beginners wanting to gain a solid understanding of the Ruby language. It starts at the beginning with how to install Ruby and work with it on multiple machines, so simply have a computer that's connected to the Internet and you'll be ready.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: Now if I always want a string to be in lower case letters, I can use the downcase method, like this.
A block of code is set as follows:
When we wish