Ruby Notes for Professionals (GoalKicker.com) (Z-Library)
Author: Ruby® group(s), company
其他
No Description
📄 File Format:
PDF
💾 File Size:
1.9 MB
60
Views
0
Downloads
0.00
Total Donations
📄 Text Preview (First 20 pages)
ℹ️
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
📄 Page
1
Ruby Notes for ProfessionalsRuby® Notes for Professionals GoalKicker.com Free Programming Books Disclaimer This is an unocial free book created for educational purposes and is not aliated with ocial Ruby® group(s) or company(s). All trademarks and registered trademarks are the property of their respective owners 200+ pages of professional hints and tricks
📄 Page
2
Contents About 1 ................................................................................................................................................................................... Chapter 1: Getting started with Ruby Language 2 .......................................................................................... Section 1.1: Hello World 2 ................................................................................................................................................. Section 1.2: Hello World as a Self-Executable File—using Shebang (Unix-like operating systems only) 2 .................................................................................................................................................................................. Section 1.3: Hello World from IRB 3 ................................................................................................................................ Section 1.4: Hello World without source files 3 .............................................................................................................. Section 1.5: Hello World with tk 3 .................................................................................................................................... Section 1.6: My First Method 4 ......................................................................................................................................... Chapter 2: Casting (type conversion) 6 ................................................................................................................. Section 2.1: Casting to a Float 6 ...................................................................................................................................... Section 2.2: Casting to a String 6 .................................................................................................................................... Section 2.3: Casting to an Integer 6 ................................................................................................................................ Section 2.4: Floats and Integers 6 ................................................................................................................................... Chapter 3: Operators 8 .................................................................................................................................................. Section 3.1: Operator Precedence and Methods 8 ........................................................................................................ Section 3.2: Case equality operator (===) 10 ................................................................................................................. Section 3.3: Safe Navigation Operator 11 ...................................................................................................................... Section 3.4: Assignment Operators 11 ........................................................................................................................... Section 3.5: Comparison Operators 12 .......................................................................................................................... Chapter 4: Variable Scope and Visibility 13 ....................................................................................................... Section 4.1: Class Variables 13 ........................................................................................................................................ Section 4.2: Local Variables 14 ....................................................................................................................................... Section 4.3: Global Variables 15 ...................................................................................................................................... Section 4.4: Instance Variables 16 .................................................................................................................................. Chapter 5: Environment Variables 18 .................................................................................................................... Section 5.1: Sample to get user profile path 18 ............................................................................................................. Chapter 6: Constants 19 ................................................................................................................................................ Section 6.1: Define a constant 19 .................................................................................................................................... Section 6.2: Modify a Constant 19 .................................................................................................................................. Section 6.3: Constants cannot be defined in methods 19 ............................................................................................ Section 6.4: Define and change constants in a class 19 .............................................................................................. Chapter 7: Special Constants in Ruby 20 .............................................................................................................. Section 7.1: __FILE__ 20 .................................................................................................................................................. Section 7.2: __dir__ 20 ................................................................................................................................................... Section 7.3: $PROGRAM_NAME or $0 20 ....................................................................................................................... Section 7.4: $$ 20 .............................................................................................................................................................. Section 7.5: $1, $2, etc 20 .................................................................................................................................................. Section 7.6: ARGV or $* 20 ............................................................................................................................................... Section 7.7: STDIN 20 ....................................................................................................................................................... Section 7.8: STDOUT 20 ................................................................................................................................................... Section 7.9: STDERR 20 .................................................................................................................................................... Section 7.10: $stderr 21 .................................................................................................................................................... Section 7.11: $stdout 21 ..................................................................................................................................................... Section 7.12: $stdin 21 ...................................................................................................................................................... Section 7.13: ENV 21 ..........................................................................................................................................................
📄 Page
3
Chapter 8: Comments 22 .............................................................................................................................................. Section 8.1: Single & Multiple line comments 22 ............................................................................................................ Chapter 9: Arrays 23 ....................................................................................................................................................... Section 9.1: Create Array of Strings 23 ........................................................................................................................... Section 9.2: Create Array with Array::new 23 ................................................................................................................ Section 9.3: Create Array of Symbols 24 ....................................................................................................................... Section 9.4: Manipulating Array Elements 24 ................................................................................................................ Section 9.5: Accessing elements 25 ................................................................................................................................ Section 9.6: Creating an Array with the literal constructor [ ] 26 ................................................................................ Section 9.7: Decomposition 26 ........................................................................................................................................ Section 9.8: Arrays union, intersection and dierence 27 ............................................................................................ Section 9.9: Remove all nil elements from an array with #compact 28 .................................................................... Section 9.10: Get all combinations / permutations of an array 28 ............................................................................. Section 9.11: Inject, reduce 29 .......................................................................................................................................... Section 9.12: Filtering arrays 30 ...................................................................................................................................... Section 9.13: #map 30 ...................................................................................................................................................... Section 9.14: Arrays and the splat (*) operator 31 ........................................................................................................ Section 9.15: Two-dimensional array 31 ........................................................................................................................ Section 9.16: Turn multi-dimensional array into a one-dimensional (flattened) array 32 ........................................ Section 9.17: Get unique array elements 32 ................................................................................................................... Section 9.18: Create Array of numbers 32 ..................................................................................................................... Section 9.19: Create an Array of consecutive numbers or letters 33 .......................................................................... Section 9.20: Cast to Array from any object 33 ............................................................................................................ Chapter 10: Multidimensional Arrays 35 ................................................................................................................ Section 10.1: Initializing a 2D array 35 ............................................................................................................................. Section 10.2: Initializing a 3D array 35 ............................................................................................................................ Section 10.3: Accessing a nested array 35 ..................................................................................................................... Section 10.4: Array flattening 35 ..................................................................................................................................... Chapter 11: Strings 37 ...................................................................................................................................................... Section 11.1: Dierence between single-quoted and double-quoted String literals 37 .............................................. Section 11.2: Creating a String 37 .................................................................................................................................... Section 11.3: Case manipulation 38 ................................................................................................................................. Section 11.4: String concatenation 38 ............................................................................................................................. Section 11.5: Positioning strings 39 .................................................................................................................................. Section 11.6: Splitting a String 40 ..................................................................................................................................... Section 11.7: String starts with 40 ..................................................................................................................................... Section 11.8: Joining Strings 40 ........................................................................................................................................ Section 11.9: String interpolation 41 ................................................................................................................................ Section 11.10: String ends with 41 ..................................................................................................................................... Section 11.11: Formatted strings 41 .................................................................................................................................. Section 11.12: String Substitution 41 ................................................................................................................................. Section 11.13: Multiline strings 41 ...................................................................................................................................... Section 11.14: String character replacements 42 ............................................................................................................ Section 11.15: Understanding the data in a string 43 ..................................................................................................... Chapter 12: DateTime 44 ............................................................................................................................................... Section 12.1: DateTime from string 44 ............................................................................................................................ Section 12.2: New 44 ......................................................................................................................................................... Section 12.3: Add/subtract days to DateTime 44 .......................................................................................................... Chapter 13: Time 46 .......................................................................................................................................................... Section 13.1: How to use the strftime method 46 ...........................................................................................................
📄 Page
4
Section 13.2: Creating time objects 46 ............................................................................................................................ Chapter 14: Numbers 47 ................................................................................................................................................ Section 14.1: Converting a String to Integer 47 .............................................................................................................. Section 14.2: Creating an Integer 47 ............................................................................................................................... Section 14.3: Rounding Numbers 47 ............................................................................................................................... Section 14.4: Even and Odd Numbers 48 ....................................................................................................................... Section 14.5: Rational Numbers 48 ................................................................................................................................. Section 14.6: Complex Numbers 48 ................................................................................................................................. Section 14.7: Converting a number to a string 49 ......................................................................................................... Section 14.8: Dividing two numbers 49 ........................................................................................................................... Chapter 15: Symbols 50 .................................................................................................................................................. Section 15.1: Creating a Symbol 50 ................................................................................................................................. Section 15.2: Converting a String to Symbol 50 ............................................................................................................. Section 15.3: Converting a Symbol to String 51 ............................................................................................................. Chapter 16: Comparable 52 ......................................................................................................................................... Section 16.1: Rectangle comparable by area 52 ........................................................................................................... Chapter 17: Control Flow 53 ......................................................................................................................................... Section 17.1: if, elsif, else and end 53 ............................................................................................................................... Section 17.2: Case statement 53 ..................................................................................................................................... Section 17.3: Truthy and Falsy values 55 ....................................................................................................................... Section 17.4: Inline if/unless 56 ........................................................................................................................................ Section 17.5: while, until 56 ............................................................................................................................................... Section 17.6: Flip-Flop operator 57 .................................................................................................................................. Section 17.7: Or-Equals/Conditional assignment operator (||=) 57 .............................................................................. Section 17.8: unless 58 ...................................................................................................................................................... Section 17.9: throw, catch 58 ............................................................................................................................................ Section 17.10: Ternary operator 58 ................................................................................................................................. Section 17.11: Loop control with break, next, and redo 59 ............................................................................................. Section 17.12: return vs. next: non-local return in a block 61 ........................................................................................ Section 17.13: begin, end 61 .............................................................................................................................................. Section 17.14: Control flow with logic statements 62 ..................................................................................................... Chapter 18: Methods 63 .................................................................................................................................................. Section 18.1: Defining a method 63 ................................................................................................................................. Section 18.2: Yielding to blocks 63 .................................................................................................................................. Section 18.3: Default parameters 64 ............................................................................................................................... Section 18.4: Optional parameter(s) (splat operator) 65 ............................................................................................. Section 18.5: Required default optional parameter mix 65 .......................................................................................... Section 18.6: Use a function as a block 66 ..................................................................................................................... Section 18.7: Single required parameter 66 ................................................................................................................... Section 18.8: Tuple Arguments 66 ................................................................................................................................... Section 18.9: Capturing undeclared keyword arguments (double splat) 67 .............................................................. Section 18.10: Multiple required parameters 67 ............................................................................................................. Section 18.11: Method Definitions are Expressions 67 .................................................................................................... Chapter 19: Hashes 69 ..................................................................................................................................................... Section 19.1: Creating a hash 69 ...................................................................................................................................... Section 19.2: Setting Default Values 70 .......................................................................................................................... Section 19.3: Accessing Values 71 ................................................................................................................................... Section 19.4: Automatically creating a Deep Hash 72 .................................................................................................. Section 19.5: Iterating Over a Hash 73 ........................................................................................................................... Section 19.6: Filtering hashes 74 ......................................................................................................................................
📄 Page
5
Section 19.7: Conversion to and from Arrays 74 ........................................................................................................... Section 19.8: Overriding hash function 74 ...................................................................................................................... Section 19.9: Getting all keys or values of hash 75 ....................................................................................................... Section 19.10: Modifying keys and values 75 ................................................................................................................. Section 19.11: Set Operations on Hashes 76 ................................................................................................................... Chapter 20: Blocks and Procs and Lambdas 77 ............................................................................................... Section 20.1: Lambdas 77 ................................................................................................................................................ Section 20.2: Partial Application and Currying 78 ........................................................................................................ Section 20.3: Objects as block arguments to methods 80 ........................................................................................... Section 20.4: Converting to Proc 80 ............................................................................................................................... Section 20.5: Blocks 81 .................................................................................................................................................... Chapter 21: Iteration 83 ................................................................................................................................................. Section 21.1: Each 83 ......................................................................................................................................................... Section 21.2: Implementation in a class 84 .................................................................................................................... Section 21.3: Iterating over complex objects 84 ............................................................................................................ Section 21.4: For iterator 85 ............................................................................................................................................. Section 21.5: Iteration with index 85 ................................................................................................................................ Section 21.6: Map 86 ......................................................................................................................................................... Chapter 22: Exceptions 87 ............................................................................................................................................ Section 22.1: Creating a custom exception type 87 ...................................................................................................... Section 22.2: Handling multiple exceptions 87 .............................................................................................................. Section 22.3: Handling an exception 88 ......................................................................................................................... Section 22.4: Raising an exception 90 ............................................................................................................................ Section 22.5: Adding information to (custom) exceptions 90 ...................................................................................... Chapter 23: Enumerators 91 ....................................................................................................................................... Section 23.1: Custom enumerators 91 ............................................................................................................................ Section 23.2: Existing methods 91 ................................................................................................................................... Section 23.3: Rewinding 91 .............................................................................................................................................. Chapter 24: Enumerable in Ruby 93 ....................................................................................................................... Section 24.1: Enumerable module 93 .............................................................................................................................. Chapter 25: Classes 96 ................................................................................................................................................... Section 25.1: Constructor 96 ............................................................................................................................................ Section 25.2: Creating a class 96 .................................................................................................................................... Section 25.3: Access Levels 96 ........................................................................................................................................ Section 25.4: Class Methods types 98 ............................................................................................................................ Section 25.5: Accessing instance variables with getters and setters 100 .................................................................. Section 25.6: New, allocate, and initialize 101 ............................................................................................................... Section 25.7: Dynamic class creation 101 ..................................................................................................................... Section 25.8: Class and instance variables 102 ............................................................................................................ Chapter 26: Inheritance 104 ......................................................................................................................................... Section 26.1: Subclasses 104 ............................................................................................................................................ Section 26.2: What is inherited? 104 ............................................................................................................................... Section 26.3: Multiple Inheritance 106 ............................................................................................................................ Section 26.4: Mixins 106 ................................................................................................................................................... Section 26.5: Refactoring existing classes to use Inheritance 107 .............................................................................. Chapter 27: method_missing 109 ............................................................................................................................. Section 27.1: Catching calls to an undefined method 109 ............................................................................................ Section 27.2: Use with block 109 ..................................................................................................................................... Section 27.3: Use with parameter 109 ............................................................................................................................
📄 Page
6
Section 27.4: Using the missing method 110 ................................................................................................................. Chapter 28: Regular Expressions and Regex Based Operations 111 ..................................................... Section 28.1: =~ operator 111 ........................................................................................................................................... Section 28.2: Regular Expressions in Case Statements 111 ........................................................................................ Section 28.3: Groups, named and otherwise 111 .......................................................................................................... Section 28.4: Quantifiers 112 ........................................................................................................................................... Section 28.5: Common quick usage 113 ........................................................................................................................ Section 28.6: match? - Boolean Result 113 ................................................................................................................... Section 28.7: Defining a Regexp 113 .............................................................................................................................. Section 28.8: Character classes 114 ............................................................................................................................... Chapter 29: File and I/O Operations 116 .............................................................................................................. Section 29.1: Writing a string to a file 116 ...................................................................................................................... Section 29.2: Reading from STDIN 116 .......................................................................................................................... Section 29.3: Reading from arguments with ARGV 116 ............................................................................................... Section 29.4: Open and closing a file 117 ...................................................................................................................... Section 29.5: get a single char of input 117 ................................................................................................................... Chapter 30: Ruby Access Modifiers 118 ................................................................................................................. Section 30.1: Instance Variables and Class Variables 118 ........................................................................................... Section 30.2: Access Controls 120 .................................................................................................................................. Chapter 31: Design Patterns and Idioms in Ruby 123 ..................................................................................... Section 31.1: Decorator Pattern 123 ................................................................................................................................ Section 31.2: Observer 124 ............................................................................................................................................... Section 31.3: Singleton 125 ............................................................................................................................................... Section 31.4: Proxy 126 ..................................................................................................................................................... Chapter 32: Loading Source Files 129 ..................................................................................................................... Section 32.1: Require files to be loaded only once 129 ................................................................................................. Section 32.2: Automatically loading source files 129 ................................................................................................... Section 32.3: Loading optional files 129 ......................................................................................................................... Section 32.4: Loading files repeatedly 130 .................................................................................................................... Section 32.5: Loading several files 130 .......................................................................................................................... Chapter 33: Thread 131 .................................................................................................................................................. Section 33.1: Accessing shared resources 131 ............................................................................................................... Section 33.2: Basic Thread Semantics 131 .................................................................................................................... Section 33.3: Terminating a Thread 132 ........................................................................................................................ Section 33.4: How to kill a thread 132 ............................................................................................................................ Chapter 34: Range 133 ................................................................................................................................................... Section 34.1: Ranges as Sequences 133 ......................................................................................................................... Section 34.2: Iterating over a range 133 ........................................................................................................................ Section 34.3: Range between dates 133 ........................................................................................................................ Chapter 35: Modules 134 ............................................................................................................................................... Section 35.1: A simple mixin with include 134 ................................................................................................................. Section 35.2: Modules and Class Composition 134 ....................................................................................................... Section 35.3: Module as Namespace 135 ...................................................................................................................... Section 35.4: A simple mixin with extend 135 ................................................................................................................ Chapter 36: Introspection in Ruby 136 ................................................................................................................... Section 36.1: Introspection of class 136 .......................................................................................................................... Section 36.2: Lets see some examples 136 .................................................................................................................... Chapter 37: Monkey Patching in Ruby 139 ........................................................................................................... Section 37.1: Changing an existing ruby method 139 ...................................................................................................
📄 Page
7
Section 37.2: Monkey patching a class 139 ................................................................................................................... Section 37.3: Monkey patching an object 139 ............................................................................................................... Section 37.4: Safe Monkey patching with Refinements 140 ........................................................................................ Section 37.5: Changing a method with parameters 140 .............................................................................................. Section 37.6: Adding Functionality 141 .......................................................................................................................... Section 37.7: Changing any method 141 ....................................................................................................................... Section 37.8: Extending an existing class 141 ................................................................................................................ Chapter 38: Recursion in Ruby 142 .......................................................................................................................... Section 38.1: Tail recursion 142 ....................................................................................................................................... Section 38.2: Recursive function 143 .............................................................................................................................. Chapter 39: Splat operator (*) 145 ........................................................................................................................... Section 39.1: Variable number of arguments 145 ......................................................................................................... Section 39.2: Coercing arrays into parameter list 145 ................................................................................................. Chapter 40: JSON with Ruby 146 .............................................................................................................................. Section 40.1: Using JSON with Ruby 146 ........................................................................................................................ Section 40.2: Using Symbols 146 .................................................................................................................................... Chapter 41: Pure RSpec JSON API testing 147 ................................................................................................... Section 41.1: Testing Serializer object and introducing it to Controller 147 ................................................................ Chapter 42: Gem Creation/Management 150 ................................................................................................... Section 42.1: Gemspec Files 150 ...................................................................................................................................... Section 42.2: Building A Gem 151 ................................................................................................................................... Section 42.3: Dependencies 151 ..................................................................................................................................... Chapter 43: rbenv 152 .................................................................................................................................................... Section 43.1: Uninstalling a Ruby 152 ............................................................................................................................. Section 43.2: Install and manage versions of Ruby with rbenv 152 ........................................................................... Chapter 44: Gem Usage 154 ....................................................................................................................................... Section 44.1: Installing ruby gems 154 ........................................................................................................................... Section 44.2: Gem installation from github/filesystem 154 ......................................................................................... Section 44.3: Checking if a required gem is installed from within code 155 .............................................................. Section 44.4: Using a Gemfile and Bundler 156 ............................................................................................................ Section 44.5: Bundler/inline (bundler v1.10 and later) 156 ........................................................................................... Chapter 45: Singleton Class 158 ............................................................................................................................... Section 45.1: Introduction 158 .......................................................................................................................................... Section 45.2: Inheritance of Singleton Class 158 .......................................................................................................... Section 45.3: Singleton classes 159 ................................................................................................................................ Section 45.4: Message Propagation with Singleton Class 159 .................................................................................... Section 45.5: Reopening (monkey patching) Singleton Classes 160 .......................................................................... Section 45.6: Accessing Singleton Class 161 ................................................................................................................. Section 45.7: Accessing Instance/Class Variables in Singleton Classes 161 .............................................................. Chapter 46: Queue 163 ................................................................................................................................................... Section 46.1: Multiple Workers One Sink 163 ................................................................................................................. Section 46.2: Converting a Queue into an Array 163 ................................................................................................... Section 46.3: One Source Multiple Workers 163 ............................................................................................................ Section 46.4: One Source - Pipeline of Work - One Sink 164 ....................................................................................... Section 46.5: Pushing Data into a Queue - #push 164 ................................................................................................. Section 46.6: Pulling Data from a Queue - #pop 165 ................................................................................................... Section 46.7: Synchronization - After a Point in Time 165 ........................................................................................... Section 46.8: Merging Two Queues 165 ......................................................................................................................... Chapter 47: Destructuring 167 ...................................................................................................................................
📄 Page
8
Section 47.1: Overview 167 ............................................................................................................................................... Section 47.2: Destructuring Block Arguments 167 ........................................................................................................ Chapter 48: Struct 168 ................................................................................................................................................... Section 48.1: Creating new structures for data 168 ...................................................................................................... Section 48.2: Customizing a structure class 168 ........................................................................................................... Section 48.3: Attribute lookup 168 .................................................................................................................................. Chapter 49: Metaprogramming 169 ....................................................................................................................... Section 49.1: Implementing "with" using instance evaluation 169 ............................................................................... Section 49.2: send() method 169 .................................................................................................................................... Section 49.3: Defining methods dynamically 170 ......................................................................................................... Section 49.4: Defining methods on instances 171 ........................................................................................................ Chapter 50: Dynamic Evaluation 172 ...................................................................................................................... Section 50.1: Instance evaluation 172 ............................................................................................................................. Section 50.2: Evaluating a String 172 ............................................................................................................................. Section 50.3: Evaluating Inside a Binding 172 ............................................................................................................... Section 50.4: Dynamically Creating Methods from Strings 173 .................................................................................. Chapter 51: instance_eval 175 ................................................................................................................................... Section 51.1: Instance evaluation 175 .............................................................................................................................. Section 51.2: Implementing with 175 ............................................................................................................................... Chapter 52: Message Passing 177 ............................................................................................................................ Section 52.1: Introduction 177 .......................................................................................................................................... Section 52.2: Message Passing Through Inheritance Chain 177 ................................................................................. Section 52.3: Message Passing Through Module Composition 178 ............................................................................ Section 52.4: Interrupting Messages 179 ....................................................................................................................... Chapter 53: Keyword Arguments 181 ..................................................................................................................... Section 53.1: Using arbitrary keyword arguments with splat operator 181 ............................................................... Section 53.2: Using keyword arguments 182 ................................................................................................................ Section 53.3: Required keyword arguments 183 .......................................................................................................... Chapter 54: Truthiness 184 .......................................................................................................................................... Section 54.1: All objects may be converted to booleans in Ruby 184 ......................................................................... Section 54.2: Truthiness of a value can be used in if-else constructs 184 ................................................................. Chapter 55: Implicit Receivers and Understanding Self 185 ...................................................................... Section 55.1: There is always an implicit receiver 185 .................................................................................................. Section 55.2: Keywords change the implicit receiver 185 ............................................................................................ Section 55.3: When to use self? 186 ............................................................................................................................... Chapter 56: Introspection 188 .................................................................................................................................... Section 56.1: View an object's methods 188 .................................................................................................................. Section 56.2: View an object's Instance Variables 189 ................................................................................................. Section 56.3: View Global and Local Variables 190 ...................................................................................................... Section 56.4: View Class Variables 190 .......................................................................................................................... Chapter 57: Refinements 192 ...................................................................................................................................... Section 57.1: Monkey patching with limited scope 192 ................................................................................................. Section 57.2: Dual-purpose modules (refinements or global patches) 192 ............................................................... Section 57.3: Dynamic refinements 193 ......................................................................................................................... Chapter 58: Catching Exceptions with Begin / Rescue 195 ......................................................................... Section 58.1: A Basic Error Handling Block 195 ............................................................................................................. Section 58.2: Saving the Error 195 .................................................................................................................................. Section 58.3: Checking for Dierent Errors 196 ............................................................................................................ Section 58.4: Retrying 197 ...............................................................................................................................................
📄 Page
9
Section 58.5: Checking Whether No Error Was Raised 198 ......................................................................................... Section 58.6: Code That Should Always Run 198 .......................................................................................................... Chapter 59: Command Line Apps 200 ..................................................................................................................... Section 59.1: How to write a command line tool to get the weather by zip code 200 .............................................. Chapter 60: IRB 201 .......................................................................................................................................................... Section 60.1: Starting an IRB session inside a Ruby script 201 .................................................................................... Section 60.2: Basic Usage 201 ........................................................................................................................................ Chapter 61: ERB 203 ......................................................................................................................................................... Section 61.1: Parsing ERB 203 .......................................................................................................................................... Chapter 62: Generate a random number 204 .................................................................................................... Section 62.1: 6 Sided die 204 ............................................................................................................................................ Section 62.2: Generate a random number from a range (inclusive) 204 .................................................................. Chapter 63: Getting started with Hanami 205 .................................................................................................... Section 63.1: About Hanami 205 ...................................................................................................................................... Section 63.2: How to install Hanami? 205 ...................................................................................................................... Section 63.3: How to start the server? 206 .................................................................................................................... Chapter 64: OptionParser 208 .................................................................................................................................... Section 64.1: Mandatory and optional command line options 208 ............................................................................. Section 64.2: Default values 209 ..................................................................................................................................... Section 64.3: Long descriptions 209 ............................................................................................................................... Chapter 65: Operating System or Shell commands 210 ............................................................................... Section 65.1: Recommended ways to execute shell code in Ruby: 210 ...................................................................... Section 65.2: Clasic ways to execute shell code in Ruby: 211 ...................................................................................... Chapter 66: C Extensions 213 ...................................................................................................................................... Section 66.1: Your first extension 213 .............................................................................................................................. Section 66.2: Working with C Structs 214 ....................................................................................................................... Section 66.3: Writing Inline C - RubyInLine 215 ............................................................................................................. Chapter 67: Debugging 217 .......................................................................................................................................... Section 67.1: Stepping through code with Pry and Byebug 217 .................................................................................. Chapter 68: Ruby Version Manager 218 ................................................................................................................ Section 68.1: How to create gemset 218 ........................................................................................................................ Section 68.2: Installing Ruby with RVM 218 ................................................................................................................... Appendix A: Installation 219 ......................................................................................................................................... Section A.1: Installing Ruby macOS 219 ......................................................................................................................... Section A.2: Gems 219 ..................................................................................................................................................... Section A.3: Linux - Compiling from source 220 ............................................................................................................ Section A.4: Linux—Installation using a package manager 220 .................................................................................. Section A.5: Windows - Installation using installer 221 ................................................................................................ Section A.6: Linux - troubleshooting gem install 221 .................................................................................................... Credits 222 ............................................................................................................................................................................ You may also like 226 ......................................................................................................................................................
📄 Page
10
GoalKicker.com – Ruby® Notes for Professionals 1 About Please feel free to share this PDF with anyone for free, latest version of this book can be downloaded from: https://goalkicker.com/RubyBook This Ruby® Notes for Professionals book is compiled from Stack Overflow Documentation, the content is written by the beautiful people at Stack Overflow. Text content is released under Creative Commons BY-SA, see credits at the end of this book whom contributed to the various chapters. Images may be copyright of their respective owners unless otherwise specified This is an unofficial free book created for educational purposes and is not affiliated with official Ruby® group(s) or company(s) nor Stack Overflow. All trademarks and registered trademarks are the property of their respective company owners The information presented in this book is not guaranteed to be correct nor accurate, use at your own risk Please send feedback and corrections to web@petercv.com
📄 Page
11
GoalKicker.com – Ruby® Notes for Professionals 2 Chapter 1: Getting started with Ruby Language Version Release Date 2.5.1 2018-03-28 2.4 2016-12-25 2.3 2015-12-25 2.2 2014-12-25 2.1 2013-12-25 2.0 2013-02-24 1.9 2007-12-25 1.8 2003-08-04 1.6.8 2002-12-24 Section 1.1: Hello World This example assumes Ruby is installed. Place the following in a file named hello.rb: puts 'Hello World' From the command line, type the following command to execute the Ruby code from the source file: $ ruby hello.rb This should output: Hello World The output will be immediately displayed to the console. Ruby source files don't need to be compiled before being executed. The Ruby interpreter compiles and executes the Ruby file at runtime. Section 1.2: Hello World as a Self-Executable File—using Shebang (Unix-like operating systems only) You can add an interpreter directive (shebang) to your script. Create a file called hello_world.rb which contains: #!/usr/bin/env ruby puts 'Hello World!' Give the script executable permissions. Here's how to do that in Unix: $ chmod u+x hello_world.rb Now you do not need to call the Ruby interpreter explicitly to run your script. $ ./hello_world.rb
📄 Page
12
GoalKicker.com – Ruby® Notes for Professionals 3 Section 1.3: Hello World from IRB Alternatively, you can use the Interactive Ruby Shell (IRB) to immediately execute the Ruby statements you previously wrote in the Ruby file. Start an IRB session by typing: $ irb Then enter the following command: puts "Hello World" This results in the following console output (including newline): Hello World If you don't want to start a new line, you can use print: print "Hello World" Section 1.4: Hello World without source files Run the command below in a shell after installing Ruby. This shows how you can execute simple Ruby programs without creating a Ruby file: ruby -e 'puts "Hello World"' You can also feed a Ruby program to the interpreter's standard input. One way to do that is to use a here document in your shell command: ruby <<END puts "Hello World" END Section 1.5: Hello World with tk Tk is the standard graphical user interface (GUI) for Ruby. It provides a cross-platform GUI for Ruby programs. Example code: require "tk" TkRoot.new{ title "Hello World!" } Tk.mainloop The result:
📄 Page
13
GoalKicker.com – Ruby® Notes for Professionals 4 Step by Step explanation: require "tk" Load the tk package. TkRoot.new{ title "Hello World!" } Define a widget with the title Hello World Tk.mainloop Start the main loop and display the widget. Section 1.6: My First Method Overview Create a new file named my_first_method.rb Place the following code inside the file: def hello_world puts "Hello world!" end hello_world() # or just 'hello_world' (without parenthesis) Now, from a command line, execute the following: ruby my_first_method.rb The output should be: Hello world! Explanation def is a keyword that tells us that we're def-ining a method - in this case, hello_world is the name of our method. puts "Hello world!" puts (or pipes to the console) the string Hello world! end is a keyword that signifies we're ending our definition of the hello_world method
📄 Page
14
GoalKicker.com – Ruby® Notes for Professionals 5 as the hello_world method doesn't accept any arguments, you can omit the parenthesis by invoking the method
📄 Page
15
GoalKicker.com – Ruby® Notes for Professionals 6 Chapter 2: Casting (type conversion) Section 2.1: Casting to a Float "123.50".to_f #=> 123.5 Float("123.50") #=> 123.5 However, there is a difference when the string is not a valid Float: "something".to_f #=> 0.0 Float("something") # ArgumentError: invalid value for Float(): "something" Section 2.2: Casting to a String 123.5.to_s #=> "123.5" String(123.5) #=> "123.5" Usually, String() will just call #to_s. Methods Kernel#sprintf and String#% behave similar to C: sprintf("%s", 123.5) #=> "123.5" "%s" % 123.5 #=> "123.5" "%d" % 123.5 #=> "123" "%.2f" % 123.5 #=> "123.50" Section 2.3: Casting to an Integer "123.50".to_i #=> 123 Integer("123.50") #=> 123 A string will take the value of any integer at its start, but will not take integers from anywhere else: "123-foo".to_i # => 123 "foo-123".to_i # => 0 However, there is a difference when the string is not a valid Integer: "something".to_i #=> 0 Integer("something") # ArgumentError: invalid value for Integer(): "something" Section 2.4: Floats and Integers 1/2 #=> 0 Since we are dividing two integers, the result is an integer. To solve this problem, we need to cast at least one of those to Float: 1.0 / 2 #=> 0.5 1.to_f / 2 #=> 0.5 1 / Float(2) #=> 0.5 Alternatively, fdiv may be used to return the floating point result of division without explicitly casting either
📄 Page
16
GoalKicker.com – Ruby® Notes for Professionals 7 operand: 1.fdiv 2 # => 0.5
📄 Page
17
GoalKicker.com – Ruby® Notes for Professionals 8 Chapter 3: Operators Section 3.1: Operator Precedence and Methods From highest to lowest, this is the precedence table for Ruby. High precedence operations happen before low precedence operations. ╔════════════════════╦═════════════════════════════════╦════════╗ ║ Operators ║ Operations ║ Method? ║ ╠════════════════════╬═════════════════════════════════╬════════╣ ║ . ║ Method call (e.g. foo.bar) ║ ║ ║ [] []= ║ Bracket Lookup, Bracket Set ║ ✓¹ ║ ║ ! ~ + ║ Boolean NOT, complement, unary plus ║ ✓² ║ ║ ** ║ Exponentiation ║ ✓ ║ ║ - ║ Unary minus ║ ✓² ║ ║ * / % ║ Multiplication, division, modulo ║ ✓ ║ ║ + - ║ Addition, subtraction ║ ✓ ║ ║ <> ║ Bitwise shift ║ ✓ ║ ║ & ║ Bitwise AND ║ ✓ ║ ║ | ^ ║ Bitwise OR, Bitwise XOR ║ ✓ ║ ║ < <= >= > ║ Comparison ║ ✓ ║ ║ <=> == != === =~ !~ ║ Equality, pattern matching, comparison ║ ✓³ ║ ║ && ║ Boolean AND ║ ║ ║ || ║ Boolean OR ║ ║ ║ .. ... ║ Inclusive range, Exclusive range ║ ║ ║ ? : ║ Ternary operator ║ ║ ║ rescue ║ Modifier rescue ║ ║ ║ = += -= ║ Assignments ║ ║ ║ defined? ║ Defined operator ║ ║ ║ not ║ Boolean NOT ║ ║ ║ or and ║ Boolean OR, Boolean AND ║ ║ ║ if unless while until ║ Modifier if, unless, while, until ║ ║ ║ { } ║ Block with braces ║ ║ ║ do end ║ Block with do end ║ ║ ╚═══════════════════╩═══════════════════════════════════╩═══════╝ Unary + and unary - are for +obj, -obj or -(some_expression). Modifier-if, modifier-unless, etc. are for the modifier versions of those keywords. For example, this is a modifier- unless expression: a += 1 unless a.zero? Operators with a ✓ may be defined as methods. Most methods are named exactly as the operator is named, for example: class Foo def **(x) puts "Raising to the power of #{x}" end def <<(y) puts "Shifting left by #{y}" end
📄 Page
18
GoalKicker.com – Ruby® Notes for Professionals 9 def ! puts "Boolean negation" end end Foo.new ** 2 #=> "Raising to the power of 2" Foo.new << 3 #=> "Shifting left by 3" !Foo.new #=> "Boolean negation" ¹ The Bracket Lookup and Bracket Set methods ([] and []=) have their arguments defined after the name, for example: class Foo def [](x) puts "Looking up item #{x}" end def []=(x,y) puts "Setting item #{x} to #{y}" end end f = Foo.new f[:cats] = 42 #=> "Setting item cats to 42" f[17] #=> "Looking up item 17" ² The "unary plus" and "unary minus" operators are defined as methods named +@ and -@, for example class Foo def -@ puts "unary minus" end def +@ puts "unary plus" end end f = Foo.new +f #=> "unary plus" -f #=> "unary minus" ³ In early versions of Ruby the inequality operator != and the non-matching operator !~ could not be defined as methods. Instead, the method for the corresponding equality operator == or matching operator =~ was invoked, and the result of that method was boolean inverted by Ruby. If you do not define your own != or !~ operators the above behavior is still true. However, as of Ruby 1.9.1, those two operators may also be defined as methods: class Foo def ==(x) puts "checking for EQUALITY with #{x}, returning false" false end end f = Foo.new x = (f == 42) #=> "checking for EQUALITY with 42, returning false" puts x #=> "false" x = (f != 42) #=> "checking for EQUALITY with 42, returning false" puts x #=> "true"
📄 Page
19
GoalKicker.com – Ruby® Notes for Professionals 10 class Foo def !=(x) puts "Checking for INequality with #{x}" end end f != 42 #=> "checking for INequality with 42" Section 3.2: Case equality operator (===) Also known as triple equals. This operator does not test equality, but rather tests if the right operand has an IS A relationship with the left operand. As such, the popular name case equality operator is misleading. This SO answer describes it thus: the best way to describe a === b is "if I have a drawer labeled a, does it make sense to put b in it?" In other words, does the set a include the member b? Examples (source) (1..5) === 3 # => true (1..5) === 6 # => false Integer === 42 # => true Integer === 'fourtytwo' # => false /ell/ === 'Hello' # => true /ell/ === 'Foobar' # => false Classes that override === Many classes override === to provide meaningful semantics in case statements. Some of them are: ╔═══════════════╦════════════════╗ ║ Class ║ Synonym for ║ ╠══════════════╬═════════════════╣ ║ Array ║ == ║ ║ ║ ║ ║ Date ║ == ║ ║ ║ ║ ║ Module ║ is_a? ║ ║ ║ ║ ║ Object ║ == ║ ║ ║ ║ ║ Range ║ include? ║ ║ ║ ║ ║ Regexp ║ =~ ║ ║ ║ ║ ║ String ║ == ║ ╚═══════════════╩════════════════╝ Recommended practice Explicit use of the case equality operator === should be avoided. It doesn't test equality but rather subsumption, and its use can be confusing. Code is clearer and easier to understand when the synonym method is used instead.
📄 Page
20
GoalKicker.com – Ruby® Notes for Professionals 11 # Bad Integer === 42 (1..5) === 3 /ell/ === 'Hello' # Good, uses synonym method 42.is_a?(Integer) (1..5).include?(3) /ell/ =~ 'Hello' Section 3.3: Safe Navigation Operator Ruby 2.3.0 added the safe navigation operator, &.. This operator is intended to shorten the paradigm of object && object.property && object.property.method in conditional statements. For example, you have a House object with an address property, and you want to find the street_name from the address. To program this safely to avoid nil errors in older Ruby versions, you'd use code something like this: if house && house.address && house.address.street_name house.address.street_name end The safe navigation operator shortens this condition. Instead, you can write: if house&.address&.street_name house.address.street_name end Caution: The safe navigation operator doesn't have exactly the same behavior as the chained conditional. Using the chained conditional (first example), the if block would not be executed if, say address was false. The safe navigation operator only recognises nil values, but permits values such as false. If address is false, using the SNO will yield an error: house&.address&.street_name # => undefined method `address' for false:FalseClass Section 3.4: Assignment Operators Simple Assignment = is a simple assignment. It creates a new local variable if the variable was not previously referenced. x = 3 y = 4 + 5 puts "x is #{x}, y is #{y}" This will output: x is 3, y is 9 Parallel Assignment Variables can also be assigned in parallel, e.g. x, y = 3, 9. This is especially useful for swapping values:
The above is a preview of the first 20 pages. Register to read the complete e-book.