The Ruby Workshop

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

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

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

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

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

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

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

7. Introduction to Ruby Gems   253

Introduction   254

RubyGems and the require Method   254

gem search 256

gem install 257

gem dependency 257

gem Versioning 258

gem list 259

Using Gems in Your Code   260

Exercise 7.01: Installing and Using a Ruby Gem   261

File I/O   262

Creating Files 262

Reading Files 263

Using the File.read Method 264

Using the File.open Method 264

Using the File.foreach Method 264

read versus open versus foreach 265

Writing to Files 265

Using the File.new Method (Initializer) 266

Using the File.open Method with a Block Method 266

Using the File.write Method 266

File.open versus File.new 267

File Modes   267

File Helpers   268

Handling CSV Data   269

Reading Data from a CSV File Using CSV.read   270

Using Column Headers as Field Names   272

Exercise 7.02: Reading Data from a .csv File and Printing a Few Columns   274

Reading Data from a .csv File Using CSV.foreach   275

Response Type Variations    276

Writing Data   277

Writing CSV Data from an Enumerable   278

Exercise 7.03: Writing an Array of Users to a CSV File   279

Service Objects   280

The Single Responsibility Principle   281

Service Objects versus Modules   282

Class Method Execution   286

Exercise 7.04: Building a Service Object   287

Activity 7.01: Presenting Voting Data in CSV Format Using Ruby Gems   288

Summary   290

8. Debugging with Ruby   293

Introduction   294

Logging and Debugging   294

Logging with the logger Class   295

Basic Logging   296

Log Levels   297

Exercise 8.01: Logging User Information   301

Exercise 8.02: Creating a Basic Exception Logger    303

Setting Log Levels by String   304

Log Output   305

STDOUT 305

STDERR 306

File 306

Log Formatting   307

Custom Date Formats 307

Custom String Formats 309

Time Zones and UTC 310

Log File Management   311

Size-Based Retention 311

Time-Based Retention 313

Exercise 8.03: Creating a Rolling Log File   314

Debugging   315

Debugging Concepts   315

Breakpoints 315

Stack Trace/Call Stack/Back Trace 317

Viewing the Stack Trace 319

StepOver, StepInto, and StepOut 319

Debugging via the CLI with byebug   321

Conditional Debugging   324

Navigating with byebug   325

Exercise 8.04: Debugging with byebug   327

Debugging with Visual Studio Code   328

Setting Breakpoints   332

Logpoints   334

The Debug Console   334

Exercise 8.05: Debugging with Visual Studio Code   336

Activity 8.01: Perform Debugging on a Voting Application   340

Summary   341

9. Ruby Beyond the Basics l   345

Introduction   346

Metaprogramming   346

Blocks   347

Syntax for Blocks   347

With do/end 347

With curly brackets ({}) 348

yield with Blocks   350

Exercise 9.01: Building a Simple Calculator   352

block_given? with Blocks   353

Exercise 9.02: Building a Flight Status Display System   354

The proc Object   356

Exercise 9.03: Performing the sum Function on a Range of Numbers    357

Exercise 9.04: Calculating Profit Using proc on an Input Price List   358

Lambdas   359

Exercise 9.05: Creating a Program to Sum a Range of Numbers Using Lambdas    359

proc versus lambda   360

The Story of the Chef and the Restaurant   361

Activity 9.01: Invoice Generator    363

Summary   364

10. Ruby Beyond the Basics ll   367

Introduction   368

Metaprogramming – A Deep Dive   368

Opening Classes   368

Exercise 10.01: Opening the Ruby String Class to Add a New Method to it   369

Monkey Patching   370

Exercise 10.02: Using Monkey Patching to Add/Subtract Values   372

method_missing   373

Exercise 10.03: Managing Ghost Methods for the Company Class   377

The Define Method   379

Exercise 10.04: Creating a Welcome Message Program Using define_method    380

HTTP Requests    381

HTTP Requests with Ruby    382

Exercise 10.05: Creating a Ruby Program to Make a Successful GET Request    382

Status Codes   383

Exercise 10.06: Creating a POST Request Using Ruby   384

Creating a Ruby Gem   386

Exercise 10.07: Creating Your Own Ruby Gem   386

Activity 10.01: Implementing GET and POST Data to an External Server   389

Summary   390

11. Introduction to Ruby on Rails l   393

Introduction   394

MVC   394

Model 395

View 395

Controller 395

Generating Our First Rails App   396

Exercise 11.01: Generating a Simple Rails Application   397

Anatomy of a Rails application   400

Exercise 11.02: Replacing the Default Page   403

Exercise 11.03: Displaying a Page Heading from the Value Served from Its Action   405

Extending Our View and Controller   406

Exercise 11.04: Adding a Resource to the Rails Application   407

Models, Migrations, and Databases   412

Exercise 11.05: Creating a Review Model for citireview   414

The Rails Console   418

Exercise 11.06: Completing the Reviews Web Application    421

The devise Ruby Gem 425

Activity 11.01: Adding Authentication for the Review Application   425

Summary   427

12. Introduction to Ruby on Rails ll   429

Introduction   430

Associations   430

belongs_to   431

has_one   432

has_many   432

has_many :through   433

has_one :through   434

has_and_belongs_to_many   435

Exercise 12.01: Creating a Model to Enable Users to Comment on Reviews on the CitiReview Application   436

Validations   443

Database Validations   443

Controller-Level Validations   443

Client-Side Validations   444

Model-Level Validations   444

Methods that Trigger Validations   444

Methods that Skip Validations   444

Checking Validations 445

Exercise 12.02: Adding Validation for the Citireview Application    445

Scaffolding    448

Exercise 12.03: Using Rails Scaffolding to Create a Rails Application for a Store with a List of Products   448

Activity 12.01: Create a Blog Application and Host It Live on a Cloud Platform   452

Summary   454

Appendix   457

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.185.87