Ruby Language
Total Page:16
File Type:pdf, Size:1020Kb
Ruby Language #ruby Table of Contents About 1 Chapter 1: Getting started with Ruby Language 2 Remarks 2 Versions 2 Examples 2 Hello World from IRB 2 Hello World with tk 3 Example code: 3 Hello World 4 Hello World without source files 4 Hello World as a Self-Executable File—using Shebang (Unix-like operating systems only) 4 My First Method 5 Overview 5 Explanation 5 Chapter 2: Arrays 6 Syntax 6 Examples 6 #map 6 Creating an Array with the literal constructor [ ] 6 Create Array of Strings 7 Create Array of Symbols 7 Create Array with Array::new 7 Manipulating Array Elements 8 Arrays union, intersection and difference 9 Filtering arrays 10 Select 10 Reject 10 Inject, reduce 10 Accessing elements 11 Two-dimensional array 12 Arrays and the splat (*) operator 12 Decomposition 13 Turn multi-dimensional array into a one-dimensional (flattened) array 15 Get unique array elements 15 Get all combinations / permutations of an array 15 Create an Array of consecutive numbers or letters 16 Remove all nil elements from an array with #compact 17 Create Array of numbers 17 Cast to Array from any object 18 Chapter 3: Blocks and Procs and Lambdas 20 Syntax 20 Remarks 20 Examples 20 Proc 20 Lambdas 21 Objects as block arguments to methods 22 Blocks 22 Yielding 23 Variables 24 Converting to Proc 24 Partial Application and Currying 25 Currying and Partial Applications 26 More useful examples of currying 26 Chapter 4: C Extensions 28 Examples 28 Your first extension 28 Working with C Structs 29 Writing Inline C - RubyInLine 30 Chapter 5: Casting (type conversion) 32 Examples 32 Casting to a String 32 Casting to an Integer 32 Casting to a Float 32 Floats and Integers 32 Chapter 6: Catching Exceptions with Begin / Rescue 34 Examples 34 A Basic Error Handling Block 34 Saving the Error 34 Checking for Different Errors 35 Retrying 36 Checking Whether No Error Was Raised 37 Code That Should Always Run 38 Chapter 7: Classes 40 Syntax 40 Remarks 40 Examples 40 Creating a class 40 Constructor 40 Class and instance variables 41 Accessing instance variables with getters and setters 42 Access Levels 43 Public Methods 43 Private Methods 44 Protected Methods 44 Class Methods types 45 Instance Methods 45 Class Method 46 Singleton Methods 46 Dynamic class creation 47 New, allocate, and initialize 48 Chapter 8: Command Line Apps 49 Examples 49 How to write a command line tool to get the weather by zip code 49 Chapter 9: Comments 51 Examples 51 Single & Multiple line comments 51 Chapter 10: Comparable 52 Syntax 52 Parameters 52 Remarks 52 Examples 52 Rectangle comparable by area 52 Chapter 11: Constants 54 Syntax 54 Remarks 54 Examples 54 Define a constant 54 Modify a Constant 54 Constants cannot be defined in methods 54 Define and change constants in a class 55 Chapter 12: Control Flow 56 Examples 56 if, elsif, else and end 56 Truthy and Falsy values 57 while, until 57 Inline if/unless 58 unless 58 Case statement 58 Loop control with break, next, and redo 60 break 60 next 61 redo 61 Enumerable iteration 62 Block result values 62 throw, catch 62 Control flow with logic statements 63 begin, end 64 return vs. next: non-local return in a block 64 Or-Equals/Conditional assignment operator (||=) 65 Ternary operator 66 Flip-Flop operator 66 Chapter 13: DateTime 68 Syntax 68 Remarks 68 Examples 68 DateTime from string 68 New 68 Add/substract days to DateTime 68 Chapter 14: Debugging 70 Examples 70 Stepping through code with Pry and Byebug 70 Chapter 15: Design Patterns and Idioms in Ruby 71 Remarks 71 Examples 71 Singleton 71 Observer 72 Decorator Pattern 73 Proxy 74 Chapter 16: Destructuring 78 Examples 78 Overview 78 Destructuring Block Arguments 78 Chapter 17: Dynamic Evaluation 79 Syntax 79 Parameters 79 Examples 79 Instance evaluation 79 Evaluating a String 80 Evaluating Inside a Binding 80 Dynamically Creating Methods from Strings 81 Chapter 18: Enumerable in Ruby 82 Introduction 82 Examples 82 Enumerable module 82 Chapter 19: Enumerators 86 Introduction 86 Parameters 86 Examples 86 Custom enumerators 86 Existing methods 86 Rewinding 87 Chapter 20: Environment Variables 88 Syntax 88 Remarks 88 Examples 88 Sample to get user profile path 88 Chapter 21: ERB 89 Introduction 89 Syntax 89 Remarks 89 Examples 89 Parsing ERB 89 Chapter 22: Exceptions 91 Remarks 91 Examples 91 Raising an exception 91 Creating a custom exception type 91 Handling an exception 92 Handling multiple exceptions 94 Adding information to (custom) exceptions 94 Chapter 23: File and I/O Operations 96 Parameters 96 Examples 96 Writing a string to a file 96 Open and closing a file 97 get a single char of input 97 Reading from STDIN 98 Reading from arguments with ARGV 98 Chapter 24: Gem Creation/Management 99 Examples 99 Gemspec Files 99 Building A Gem 100 Dependencies 100 Chapter 25: Gem Usage 101 Examples 101 Installing ruby gems 101 Specifying versions 101 Gem installation from github/filesystem 102 Checking if a required gem is installed from within code 102 Using a Gemfile and Bundler 103 Bundler/inline (bundler v1.10 and later) 104 Chapter 26: Generate a random number 105 Introduction 105 Remarks 105 Examples 105 6 Sided die 105 Generate a random number from a range (inclusive) 105 Chapter 27: Getting started with Hanami 106 Introduction 106 Examples 106 About Hanami 106 How to install Hanami? 106 How to start the server? 107 Chapter 28: Hashes 110 Introduction 110 Syntax 110 Remarks 110 Examples 110 Creating a hash 110 Accessing Values 111 Setting Default Values 113 Automatically creating a Deep Hash 114 Modifying keys and values 115 Iterating Over a Hash 115 Conversion to and from Arrays 116 Getting all keys or values of hash 117 Overriding hash function 117 Filtering hashes 118 Set Operations on Hashes 118 Chapter 29: Implicit Receivers and Understanding Self 120 Examples 120 There is always an implicit receiver 120 Keywords change the implicit receiver 121 When to use self? 121 Chapter 30: Inheritance 123 Syntax 123 Examples 123 Refactoring existing classes to use Inheritance 123 Multiple Inheritance 124 Subclasses 124 Mixins 124 What is inherited? 125 Chapter 31: Installation 128 Examples 128 Linux - Compiling from source 128 Linux—Installation using a package manager 128 Windows - Installation using installer 128 Gems 129 Linux - troubleshooting gem install 129 Installing Ruby macOS 130 Chapter 32: instance_eval 132 Syntax 132 Parameters 132 Examples 132 Instance evaluation 132 Implementing with 133 Chapter 33: Introspection 134 Examples 134 View an object's methods 134 Inspecting an Object 134 Inspecting a Class or Module 135 View an object's Instance Variables 135 View Global and Local Variables 136 View Class Variables 137 Chapter 34: Introspection in Ruby 138 Introduction 138 Examples 138 Lets see some examples 138 Introspection of class 140 Chapter 35: IRB 141 Introduction 141 Parameters 141 Examples 142 Basic Usage 142 Starting an IRB session inside a Ruby script 142 Chapter 36: Iteration 143 Examples 143 Each 143 Method 1: Inline 143 Method 2: Multiline 143 Implementation in a class 144 Map 144 Iterating over complex objects 145 For iterator 146 Iteration with index 146 Chapter 37: JSON with Ruby 147 Examples 147 Using JSON with Ruby 147 Using Symbols 147 Chapter 38: Keyword Arguments 148 Remarks 148 Examples 148 Using keyword arguments 149 Required keyword arguments 150 Using arbitrary keyword arguments with splat operator 150 Chapter 39: Loading Source Files 152 Examples 152 Require files to be loaded only once 152 Automatically loading source files 152 Loading optional files 152 Loading files repeatedly 153 Loading several files 153 Chapter 40: Message Passing 154 Examples 154 Introduction 154 Message Passing Through Inheritance Chain 154 Message Passing Through Module Composition 155 Interrupting Messages 156 Chapter 41: Metaprogramming 158 Introduction 158 Examples 158 Implementing "with" using instance evaluation 158 Defining methods dynamically 158 Defining methods on instances 159 send() method 159 Here is the more descriptive example 160 Chapter 42: method_missing 161 Parameters 161 Remarks 161 Examples 162 Catching calls to an undefined method 162 Using the missing method 162 Use with block 162 Use with parameter 162 Chapter 43: Methods 164 Introduction 164 Remarks 164 Overview of Method Parameters 164 Examples 165 Single required parameter 165 h11 165 Multiple required parameters 165 h12 165 Default parameters 166 h13 166 Optional parameter(s) (splat operator) 166 h14 167 Required default optional parameter mix 167 Method Definitions are Expressions 167 Capturing undeclared keyword arguments (double splat) 168 Yielding to blocks 169 Tuple Arguments 170 Defining a method 170 Use a function as a block 171 Chapter 44: Modules 172 Syntax 172 Remarks 172 Examples 172 A simple mixin with include 172 Module as Namespace 173 A simple mixin with extend 173 Modules and Class Composition 173 Chapter 45: Monkey Patching in Ruby 175 Introduction 175 Remarks 175 Examples 175 Changing any method 175 Changing an existing ruby method 175 Changing a method with parameters 175 Extending an existing class 176 Safe Monkey patching with Refinements 176 Chapter 46: Monkey Patching in Ruby 178 Examples 178 Monkey patching a class 178 Monkey patching an object 178 Chapter 47: Monkey Patching in Ruby 179 Remarks 179 Examples 179 Adding Functionality 179 Chapter 48: Multidimensional Arrays 180 Introduction 180 Examples 180 Initializing a 2D array 180 Initializing a 3D array 180 Accessing a nested array 180 Array flattening 181 Chapter 49: Numbers 182 Remarks 182 Numbers hierarchy 182 Examples 182 Creating an Integer 182 Converting a String to Integer 182 Converting a number to a string 183 Dividing two numbers 183 Rational Numbers 184 Complex Numbers 184 Even and Odd Numbers 184 Rounding Numbers 185 Chapter 50: Operating System or Shell commands 186 Introduction 186 Remarks 186 Examples 187 Recommended ways to execute shell code in Ruby: 187 Clasic ways to execute shell code in Ruby: 188 Chapter 51: Operators 190 Remarks 190 Operators are methods 190 When to use && vs.