Table Of ContentThe Ruby Workshop
A Practical, No-Nonsense Introduction
to Ruby Development
Akshat Paul
Peter Philips
Dániel Szabó
Cheyne Wallace
The Ruby Workshop
Copyright © 2019 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 authors, 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.
Authors: Akshat Paul, Peter Philips, Dániel Szabó, and Cheyne Wallace
Technical Reviewers: Jonathan Evans, Jagdish Narayandasani, and Dixitkumar N. Patel
Managing Editor: Snehal Tambe
Acquisitions Editor: Alicia Wooding
Production Editor: Samita Warang
Editorial Board: Shubhopriya Banerjee, Bharat Botle, Ewan Buckingham, Megan Carlisle,
Mahesh Dhyani, Manasa Kumar, Alex Mazonowicz, Bridget Neale, Dominic Pereira,
Shiny Poojary, Abhishek Rane, Erol Staveley, Ankita Thakur, Nitesh Thakur,
and Jonathan Wray
First Published: October 2019
Production Reference: 1301019
ISBN: 978-1-83864-236-5
Published by Packt Publishing Ltd.
Livery Place, 35 Livery Street
Birmingham B3 2PB, UK
Table of Contents
Preface i
Chapter 1: Writing and Running Ruby Programs 1
Introduction .................................................................................................... 2
Key Features of Ruby ........................................................................................... 2
Object-Oriented ...............................................................................................3
Interpreted Language .....................................................................................3
Duck Typing and Dynamic Typing ..................................................................4
Multi-paradigm Language ...............................................................................4
Reflection ..........................................................................................................5
Metaprogramming ...........................................................................................5
Interactive Ruby Shell (IRB) .......................................................................... 6
Exercise 1.01: Creating and Assigning Variables .............................................. 7
Exercise 1.02: Assigning a Variable of One Data Type to a Different Type ... 8
Exercise 1.03: Getting the Type of a Variable ................................................... 9
Getting the Details of the Public Methods of an Object ............................... 10
Running Ruby Code from Ruby Files ............................................................... 10
Exercise 1.04: Getting User Input in a Ruby Program ................................... 11
Standard Data Types ................................................................................... 12
Number ............................................................................................................... 12
Exercise 1.05: Performing Common Integer Operations .............................. 14
Exercise 1.06: Using Common Integer Methods to Perform Complex
Arithmetic .......................................................................................................... 15
Floating-Point Numbers .................................................................................... 17
Exercise 1.07: Performing Common Operations
for Floating-Point Numbers .............................................................................. 17
String ................................................................................................................... 19
Exercise 1.08: Using Common String Methods .............................................. 21
Exercise 1.09: Performing String Concatenation .......................................... 24
Exercise 1.10: Performing String Interpolation .............................................. 26
Exercise 1.11: Extracting and Searching a Substring from a String ............. 26
Exercise 1.12: Replacing Part of a String with Another String ...................... 27
Exercise 1.13: Replacing All the Values inside a String Using gsub .............. 28
Exercise 1.14: Splitting a String and Joining a String ..................................... 29
Activity 1.01: Generating Email Addresses Using Ruby ................................. 30
Boolean ............................................................................................................... 31
Activity 1.02: Calculating the Area and Perimeter
of a Candy Manufacturing Plant ...................................................................... 32
Summary ....................................................................................................... 32
Chapter 2: Ruby Data Types and Operations 35
Introduction ................................................................................................. 36
Arrays ............................................................................................................ 36
Iterating Through an Array ............................................................................... 38
Operations on Arrays ........................................................................................ 42
Merging Two Arrays ......................................................................................42
Removing Occurrences of Similar Elements from an Array ....................42
Inserting Elements into an Array at the End .............................................43
Finding the Last Element of an Array without Modifying It ....................43
Finding the Last Element of an Array and Removing it ............................44
Exercise 2.01: Performing Simple Operations on Arrays .............................. 44
Creating an Array That Cannot Be Modified .............................................47
Finding All the Unique Elements in an Array .............................................47
Sorting the Elements of an Array ................................................................48
Finding the Number of Elements in an Array ............................................49
Establishing Whether an Element Exists in an Array (Case-Sensitive) ..49
Converting Elements of an Array into a String ..........................................50
Exercise 2.02: Performing Complex Operations on Arrays ........................... 51
Hashes ........................................................................................................... 53
Operations on Hashes ....................................................................................... 58
Getting Values from the Hash ....................................................................59
Sorting a Hash ..............................................................................................59
Merging Hashes.............................................................................................60
Retrieving Keys or Values from a Hash ......................................................61
Deleting a Value from a Hash by Key .........................................................61
Removing or Rejecting Elements from a Hash ..........................................62
Establishing whether a Hash Contains a Particular Value .......................62
Exercise 2.03: Converting a Time String to a Hash ........................................ 63
Ruby Methods .............................................................................................. 64
Passing Arguments to a Method ...................................................................... 65
Ruby Methods with Default Values ................................................................. 65
Return Value(s) from Methods ......................................................................... 69
Naming Conventions for Methods ................................................................... 71
Activity 2.01: Dice Roller Program .................................................................... 72
Summary ....................................................................................................... 73
Chapter 3: Program Flow 75
Introduction .................................................................................................. 76
Boolean Operators ...................................................................................... 76
The AND Operator ........................................................................................77
The OR Operator ...........................................................................................78
The NOT Operator ........................................................................................79
Truth Tables ........................................................................................................ 79
Truthiness ........................................................................................................... 81
Precedence ......................................................................................................... 84
Exercise 3.01: Implementing Boolean Operators .......................................... 86
Conditional Expressions .................................................................................... 87
The if Statement ............................................................................................87
The else Statement .......................................................................................88
The elsif Statement .......................................................................................88
The unless Statement ...................................................................................89
Comparison .................................................................................................. 90
Comparison Operators ...................................................................................... 90
Comparing Strings ............................................................................................. 92
Exercise 3.02: Creating a Method to Check Your Balance ............................ 93
The case/when Statement ................................................................................ 94
The === Operator ............................................................................................... 96
The Ternary Operator ................................................................................. 97
Exercise 3.03: Speed Determiner ..................................................................... 98
Loops ........................................................................................................... 103
The while/do Loop .......................................................................................... 103
Exercise 3.04: Developing a Mind Reader .................................................... 104
The until/do Loop ............................................................................................ 108
The do/while Loop .......................................................................................... 108
Iterators and Enumerators ............................................................................ 110
The each Method ........................................................................................110
The each_with_index Method ....................................................................112
The map/collect Loop .................................................................................114
Exercise 3.05: Developing an Arbitrary Math Method ................................ 117
Activity 3.01: Number-Guessing Game ......................................................... 119
Summary ..................................................................................................... 121
Chapter 4: Ruby Methods 123
Introduction ................................................................................................ 124
The Basic Structure of the Ruby Method ................................................ 125
Method Components: Signature and Implementation .............................. 126
The Method Signature .................................................................................... 126
Method Arguments ......................................................................................... 128
Positional Arguments ..................................................................................... 128
Variable Scope ................................................................................................. 129
Optional Parentheses and Code Style .......................................................... 131
Mandatory and Optional Arguments ........................................................... 132
Keyword Arguments ....................................................................................... 133
Return Values ............................................................................................. 134
Multiple Return Values ................................................................................... 134
Exercise 4.01: Performing Operations on an Array .................................... 137
The Splat Operator .................................................................................... 139
The Single Splat (*) Operator .....................................................................139
The Double Splat (**) Operator .................................................................140
Exercise 4.02: Creating a Method to Take Any Number of Parameters ... 141
Duck Typing ................................................................................................ 143
Sending a Message .................................................................................... 144
Using Built-In Modules: Time and Math ....................................................... 146
Math ................................................................................................................. 146
Exercise 4.03: Using the Math Library to Perform
Mathematical Operations .............................................................................. 146
Time .................................................................................................................. 150
Exercise 4.04: Performing Method Operations with the Time Module .... 151
Activity 4.01: Blackjack Card Game ............................................................... 154
Summary ..................................................................................................... 156
Chapter 5: Object-Oriented programming with Ruby 159
Introduction ................................................................................................ 160
Classes and Objects ................................................................................... 161
Instance Methods ........................................................................................... 162
Getters and Setters .................................................................................... 164
Exercise 5.01: Modeling a Company's Organizational Chart
Using Classes ................................................................................................... 167
Class Methods ................................................................................................. 174
Method 1: Calling a Method Directly on the Class ..................................175
Method 2: Using the self Keyword ............................................................175
Class Variables ................................................................................................. 176
Exercise 5.02: Generating URLs for Sharing Content
on Social Platforms ......................................................................................... 179
Inheritance ................................................................................................. 183
The Inheritance of Methods .......................................................................... 184
The Inheritance of Variables ......................................................................... 187
Calling super .................................................................................................... 188
The Different Ways to Call super .................................................................. 190
Calling super without Arguments .............................................................191
Calling super with Arguments ...................................................................191
Calling super with the Naked Splat Operator .........................................191
Exercise 5.03: Modelling a Class for Location Addresses ........................... 195
Encapsulation ............................................................................................. 198
Public Methods ............................................................................................198
Private Methods ..........................................................................................199
Protected Methods .....................................................................................200
Exercise 5.04: Demonstrate the Visibility Rules of Ruby Methods ........... 201
Bypassing Visibility ......................................................................................... 207
A Quick Note about File Organization ......................................................209
Activity 5.01: Voting Application for Employee of the Month ................... 209
Summary ..................................................................................................... 211
Chapter 6: Modules and Mixins 213
Introduction ................................................................................................ 214
Including Modules ..................................................................................... 214
Exercise 6.01: Controlling the Operations of Services
in an Application ............................................................................................. 217
Inheritance with Module Methods ............................................................... 218
Inclusion Ordering .......................................................................................... 220
extend ......................................................................................................... 221
Exercise 6.02: Extending Your Modules with Class
and Instance Methods .................................................................................... 223
Module Callbacks ............................................................................................ 226
Exercise 6.03: Using Module Functions to Extend Classes ......................... 227
Importing Modules as Class Methods using Extended .............................. 229
Combining include and extend ..................................................................... 229
Enumerated Types .......................................................................................... 231
Exercise 6.04: Writing a Module to Define Payment Methods
for a Product Application ............................................................................... 232
Module Methods ........................................................................................ 237
Namespaces ............................................................................................... 238
Exercise 6.05: How to Reuse Constants with a Namespace ...................... 240
prepend ....................................................................................................... 242
prepend with Subclasses ............................................................................... 244
Exercise 6.06: Prepending Modules to Classes ............................................ 248
Activity 6.01: Implementing Categories on the Voting
Application Program ...................................................................................... 249
Summary ..................................................................................................... 250