Ruby Pocket Reference, 2nd Edition Instant Help for Ruby Programmers (Michael Fitzgerald) (Z-Library)

Author: Michael Fitzgerald

科学

Updated for Ruby 2.2, this handy reference offers brief yet clear explanations of Ruby's core elements - from operators to blocks to documentation creation—and highlights the key features you may work with every day. Need to know the correct syntax for a conditional? Forgot the name of that String method? This book is organized to help you find the facts fast. Ruby Pocket Reference, 2nd Edition is ideal for experienced programmers who are new to Ruby. Whether you've come to Ruby because of Rails, or you want to take advantage of this clean, powerful, and expressive language for other applications, this reference will help you easily pinpoint the information you need.

📄 File Format: PDF
💾 File Size: 2.3 MB
15
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
Michael Fitzgerald Ruby Pocket Reference INSTANT HELP FOR RUBY PROGRAMMERS 2nd Edition Ruby Pocket Reference Fitzgerald ISBN: 978-1-491-92601-7 US $14.99 CAN $17.99 Updated for Ruby 2.2, this handy reference offers brief yet clear explana- tions of Ruby’s core elements—from operators to blocks to documentation creation—and highlights the key features you may work with every day. Need to know the correct syntax for a conditional? Forgot the name of that String method? This book is organized to help you find the facts fast. Ruby Pocket Reference, 2nd Edition is ideal for experienced programmers who are new to Ruby. Whether you’ve come to Ruby because of Rails, or you want to take advantage of this clean, powerful, and expressive language for other applications, this reference will help you easily pinpoint the information you need. You’ll find detailed reference material for: ■ Keywords, operators, comments, numbers, and symbols ■ Variables, pre-defined global variables, and regular expressions ■ Conditional statements, method use, classes, and exception handling ■ Methods for the BasicObject, Object, Kernel, String, Array, and Hash classes ■ Time formatting directives ■ New syntax since Ruby 1.9 Michael Fitzgerald is an author, coder, and novelist who has written over 20 books. He is the author of O’Reilly’s Learning Ruby, Learning XSLT, and XML Hacks, and co-author on the XML Pocket Reference. oreilly.com, Twitter: @oreillymedia Ruby Pocket Reference PROGR AMMING L ANGUAGES / RUBY SECOND EDITION www.it-ebooks.info
📄 Page 2
Michael Fitzgerald Ruby Pocket Reference INSTANT HELP FOR RUBY PROGRAMMERS 2nd Edition Ruby Pocket Reference Fitzgerald ISBN: 978-1-491-92601-7 US $14.99 CAN $17.99 Updated for Ruby 2.2, this handy reference offers brief yet clear explana- tions of Ruby’s core elements—from operators to blocks to documentation creation—and highlights the key features you may work with every day. Need to know the correct syntax for a conditional? Forgot the name of that String method? This book is organized to help you find the facts fast. Ruby Pocket Reference, 2nd Edition is ideal for experienced programmers who are new to Ruby. Whether you’ve come to Ruby because of Rails, or you want to take advantage of this clean, powerful, and expressive language for other applications, this reference will help you easily pinpoint the information you need. You’ll find detailed reference material for: ■ Keywords, operators, comments, numbers, and symbols ■ Variables, pre-defined global variables, and regular expressions ■ Conditional statements, method use, classes, and exception handling ■ Methods for the BasicObject, Object, Kernel, String, Array, and Hash classes ■ Time formatting directives ■ New syntax since Ruby 1.9 Michael Fitzgerald is an author, coder, and novelist who has written over 20 books. He is the author of O’Reilly’s Learning Ruby, Learning XSLT, and XML Hacks, and co-author on the XML Pocket Reference. oreilly.com, Twitter: @oreillymedia Ruby Pocket Reference PROGR AMMING L ANGUAGES / RUBY SECOND EDITION www.it-ebooks.info
📄 Page 3
Michael Fitzgerald Ruby Pocket Reference SECOND EDITION www.it-ebooks.info
📄 Page 4
978-1-491-92601-7 [LSI] Ruby Pocket Reference by Michael Fitzgerald Copyright © 2015 Michael Fitzgerald. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promo‐ tional use. Online editions are also available for most titles (http://safaribook‐ sonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Editor: Brian MacDonald Production Editors: Colleen Lobner and Nicole Shelby Copyeditor: Gillian McGarvey Proofreader: Kim Cofer Indexer: WordCo Indexing Services Interior Designer: David Futato Cover Designer: Ellie Volckhausen Illustrator: Rebecca Demarest July 2007: First Edition August 2015: Second Edition Revision History for the Second Edition 2015-08-05: First Release 2015-10-23: Second Release See http://oreilly.com/catalog/errata.csp?isbn=9781491926017 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Ruby Pocket Reference, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellec‐ tual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. www.it-ebooks.info
📄 Page 5
Table of Contents Introduction 1 Conventions Used in This Book 1 Using Code Examples 2 Safari® Books Online 3 How to Contact Us 4 Acknowledgments 4 Running Ruby 5 Interactive Ruby (irb) 8 Ruby’s Keywords 14 Ruby’s Operators 17 Comments 19 Numbers 20 Variables 22 Symbols 24 Predefined Global Variables 25 Keyword Literals 29 Global Constants 30 Ranges 31 Methods 32 Conditional Statements 41 iii www.it-ebooks.info
📄 Page 6
Classes 51 Files 64 The IO Class 69 Exception Handling 72 BasicObject Class 75 Object Class 76 Kernel Module 82 String Class 98 Array Class 147 Hash Class 165 Time Formatting Directives 173 Ruby Documentation 176 RubyGems 183 Rake 185 Ruby Resources 188 Glossary 191 Index 209 iv | Table of Contents www.it-ebooks.info
📄 Page 7
Ruby Pocket Reference Introduction Ruby is an open source, object-oriented scripting language cre‐ ated by Yukihiro “Matz” Matsumoto and initially released in Japan in 1995. Ruby has since gained worldwide acceptance as an easy-to-learn, powerful, and expressive programming lan‐ guage. An interpreted language, Ruby runs on all major plat‐ forms. For the latest information on Ruby, see http://www.ruby- lang.org. For online Ruby documentation, see http://ruby- doc.org. This edition of the Ruby Pocket Reference supports version 2.2.2 of Ruby, the current version at the time of writing. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function 1 www.it-ebooks.info
📄 Page 8
names, databases, data types, environment variables, state‐ ments, and keywords. Constant width bold Shows commands or other text that should be typed liter‐ ally by the user. Constant width italic Shows text that should be replaced with user-supplied val‐ ues or by values determined by context. NOTE This element signifies a general note. Using Code Examples Supplemental material (code examples, exercises, etc.) is avail‐ able for download at https://github.com/michaeljamesfitzgerald/ Ruby-Pocket-Reference-2nd-Edition. This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permis‐ sion. Incorporating a significant amount of example code from this book into your product’s documentation does require per‐ mission. 2 | Ruby Pocket Reference www.it-ebooks.info
📄 Page 9
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Ruby Pocket Reference, 2nd Edition by Michael Fitz‐ gerald (O’Reilly). Copyright 2015 Michael Fitzgerald, 978-1-4919-2601-7.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permis‐ sions@oreilly.com. Safari® Books Online Safari Books Online is an on-demand digital library that delivers expert content in both book and video form from the world’s leading authors in technology and busi‐ ness. Technology professionals, software developers, web designers, and business and creative professionals use Safari Books Online as a primary resource for research, problem solving, learning, and certification training. Safari Books Online offers a range of plans and pricing for enterprise, government, education, and individuals. Members have access to thousands of books, training videos, and prepublication manuscripts in one fully searchable data‐ base from publishers like O’Reilly Media, Prentice Hall Profes‐ sional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technology, and hun‐ dreds more. For more information about Safari Books Online, please visit us online. Safari® Books Online | 3 www.it-ebooks.info
📄 Page 10
How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, exam‐ ples, and any additional information. You can access this page at http://bit.ly/ruby-pocket-ref-2e. To comment or ask technical questions about this book, send email to bookquestions@oreilly.com. For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com. Find us on Facebook: http://facebook.com/oreilly Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia Acknowledgments The second edition of this book is dedicated to the memory of my brother Mark S. Fitzgerald (1955–2012). I want to thank Simon St. Laurent for helping to make this book happen and Brian MacDonald for his patient support while I wrote this new edition. I also want to thank my techni‐ cal reviewers, Justin Page and Mike Korcynski, who essentially busted my technical chops. Thanks, guys. 4 | Ruby Pocket Reference www.it-ebooks.info
📄 Page 11
Running Ruby Test whether Ruby is available on your computer by typing the following at a command or shell prompt: $ ruby --version The response you get from this command should look similar to the following (if running Mac OS X Yosemite): ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin14] You can install Ruby on any of the major platforms—Windows, Mac, or flavors of Linux. For Ruby file archives and installation instructions, see http://www.ruby-lang.org/en/downloads and https://www.ruby-lang.org/en/documentation/installation/. To manage multiple versions of Ruby on a single computer, con‐ sider using Ruby Version Manager or RVM (http://rvm.io) or rbenv (https://github.com/sstephenson/rbenv). To easily and straightforwardly install the latest version of Ruby on a Mac, try Homebrew (http://brew.sh). Running the Ruby Interpreter View Ruby switches (command-line options) by entering: $ ruby --help Or, for a shorter message: $ ruby -h Usage: ruby [switches] [--] [programfile] [arguments] -0 [octal] Specify a record separator (\0 if no argument). -a Autosplit mode with -n or -p (splits $_ into $F). -c Check program syntax only (replies Syntax OK). Running Ruby | 5 www.it-ebooks.info
📄 Page 12
-Cdirectory cd to directory before executing script. -d [or] --debug Set debugging flags (sets predefined variable $DEBUG to true). -e 'command' Execute one line of script; more than one -e allowed; omit programfile. -Eex[:in] [or] --encoding=ex[:in] Specify the default internal and external character encod‐ ings. -Fpattern split() pattern for autosplit (-a). -iextension Edit ARGV files in place (make backup if optional extension supplied). -Idirectory Specify $LOAD_PATH (predefined variable) directory; may be used more than once. -l Enable line-ending processing. -n Assume 'while gets(); ... end' loop around your script. -p Assume loop like -n but print line also like sed. -rlibrary Require library before executing your script. -s Enable some switch parsing for switches after script name. 6 | Ruby Pocket Reference www.it-ebooks.info
📄 Page 13
-S Look for the script using PATH environment variable. -T[level=1] Turn on tainting checks. -v [or] --verbose Print version information, then turn on verbose mode (compare --version). -w Turn on warnings for script. -W[level=2] Set warning level: 0 = silence, 1 = medium, and 2 = ver‐ bose (default). -x[directory] Strip off text before #! (shebang) line, and optionally cd to directory. --copyright Print the Ruby copyright message. --enable=feature[, . . .] [or] --disable=feature[, . . .] Enable or disable features. See “Features.” --external-encoding=encoding [or] --internal-encoding=encoding Specify the default external or internal character encoding. --version Print version information (compare -v). --help Show this help message (compare -h [short message]). Features: gems Rubygems (default: enabled). rubyopt RUBYOPT environment variable (default: enabled). Running Ruby | 7 www.it-ebooks.info
📄 Page 14
Interactive Ruby (irb) Interactive Ruby, or irb, is an interactive programming envi‐ ronment that comes with Ruby. It was written by Keiju Ishit‐ suka. To invoke it, type irb at a shell or command prompt, and begin entering Ruby statements and expressions. Use exit or quit to exit. See http://ruby-doc.org/stdlib-2.2.2/libdoc/irb/rdoc/ index.html. Usage: irb[.rb] [options] [programfile] [arguments] For example, to get the current version of irb, use: irb --version # => irb 0.9.6(09/06/30) Options: -f Suppress reading of the file ˜/.irbrc. -m bc mode (mathn, fraction, or matrix available). [Note that mathn is deprecated as of 2.2.] -d Set $DEBUG to true (same as ruby -d). -r load-module Same as ruby -r. -I path Specify $LOAD_PATH directory. -U Same as ruby -U. -E enc Same as ruby -E. -w Same as ruby -w. 8 | Ruby Pocket Reference www.it-ebooks.info
📄 Page 15
-W[level=2] Same as ruby -W. --context-mode n Set n[0–3] to method to create binding object when new workspace created. --echo Show result (default). --noecho Don’t show result. --inspect Use inspect for output (default except for bc mode). --noinspect Don’t use inspect for output. --readline Use Readline extension module. --noreadline Don’t use Readline extension module. --prompt prompt-mode (--prompt-mode prompt-mode) Switch prompt mode. Predefined prompt modes are default, simple, xmp, and inf-ruby. --inf-ruby-mode Use prompt appropriate for inf-ruby-mode on Emacs. Suppresses --readline. --sample-book-mode (--simple-prompt) Simple prompt mode. --noprompt No prompt mode. --single-irb Share self with sub-irb. Interactive Ruby (irb) | 9 www.it-ebooks.info
📄 Page 16
--tracer Display trace for each execution of command. --back-trace-limit n Display backtrace top n and tail n. The default value is 16. --irb_debug n Set internal debug level to n (not commonly used). --verbose Show details. --noverbose Don’t show details. -v (--version). Print the version of irb. -h (--help). Print help. -- Separate options of irb from list of command-line arguments. Following is a sample of expressions evaluated by irb: $ irb --noprompt 23 + 27 50 50 - 23 27 10 * 5 50 10**5 100000 50 / 5 10 x = 1 1 x + 59 60 hi = "Hello, Matz!" "Hello, Matz!" hi.each_char { |s| print s } Hello, Matz!=> "Hello, Matz!" 10 | Ruby Pocket Reference www.it-ebooks.info
📄 Page 17
1.upto( 10 ) { |n| print n, " " } 1 2 3 4 5 6 7 8 9 10 => 1 100 < 1_000 true class Hello attr :hi, true end nil h = Hello.new #<Hello:0x3602cc> h.hi = "Hello, Matz!" "Hello, Matz!" h.hi "Hello, Matz!" self main self.class Object exit # or quit You can also invoke a single program with irb. After running the program, irb exits: $ cat hello.rb #!/usr/bin/env ruby class Hello def initialize( hello ) @hello = hello end def hello @hello end end salute = Hello.new( "Hello, Matz!" ) puts salute.hello $ irb hello.rb hello.rb(main):001:0> #!/usr/bin/env ruby hello.rb(main):002:0* hello.rb(main):003:0* class Hello hello.rb(main):004:1> def initialize( hello ) hello.rb(main):005:2> @hello = hello hello.rb(main):006:2> end hello.rb(main):007:1> def hello hello.rb(main):008:2> @hello hello.rb(main):009:2> end hello.rb(main):010:1> end Interactive Ruby (irb) | 11 www.it-ebooks.info
📄 Page 18
=> nil hello.rb(main):011:0> hello.rb(main):012:0* salute = Hello.new( "Hello, Matz!" ) => #<Hello:0x007fd28b036f50 @hello="Hello, Matz!"> => #<Hello:0x319f20 @hello="Hello, Matz!"> hello.rb(main):013:0> puts salute.hello Hello, Matz! => nil hello.rb(main):014:0> $ When running any code that follows in this book, you can run it either in irb or with the Ruby interpreter, unless another one is specified. Using a Shebang Comment on Unix/Linux Use a shebang comment on the first line of a Ruby program to help a Unix/Linux system execute the commands in a program file according to a specified interpreter, Ruby. Keep in mind that this does not work on Windows. Listed here is a very short program named hi.rb with a shebang on the first line: #!/usr/bin/env ruby puts "Hi, world!" Other possible shebang lines or comments are #!/usr/bin/ruby -w (warnings on) or #!/usr/local/bin/ruby. The location of the Ruby executable could vary given that you might be using a version manager like RVM and rbenv. With a shebang in place, you can type the name of the executable script, followed by Return or Enter, at a shell prompt without invoking the Ruby interpreter directly: $ ./hello.rb TIP Make sure the file is executable with chmod +x. 12 | Ruby Pocket Reference www.it-ebooks.info
📄 Page 19
Associating File Types on Windows Windows doesn’t know or care about a shebang comment (#!), but you can achieve a similar result by creating a file type asso‐ ciation with the assoc and ftype commands on Windows (DOS). To find out whether an association exists for the file extension .rb, use the assoc command: C:\Ruby Code>assoc .rb File association not found for extension .rb If it’s not found, associate the .rb extension with a file type like this: C:\Ruby Code>assoc .rb=rbFile Then test again whether the association exists: C:\Ruby Code>assoc .rb .rb=rbFile Now test to see whether the file type for Ruby exists with ftype: C:\Ruby Code>ftype rbfile File type 'rbfile' not found or no open command associated with it. If not found, you can create it with a command like this, depending on where Ruby is located on your machine: C:\Ruby Code>ftype rbfile="C:\Program Files\Ruby\bin \ruby.exe" "%1" %* Be sure to put the correct path to the executable for the Ruby interpreter, followed by the substitution variables. %1 is a sub‐ stitution variable for the file you want to run; %* accepts all other parameters that may appear on the command line. Test it: C:\Ruby Code>ftype rbfile rbfile="C:\Program Files\Ruby \bin\ruby.exe" "%1" %* Finally, add .rb to the PATHEXT environment variable. See whether it is there already with set: C:\Ruby Code>set PATHEXT PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE; .WSF;.WSH;.tcl Interactive Ruby (irb) | 13 www.it-ebooks.info
📄 Page 20
If it is not there, add it like this: C:\Ruby Code>set PATHEXT=.rb;%PATHEXT% Then test again: C:\Ruby Code>set PATHEXT PATHEXT=.rb;.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE; .WSF;.WSH;.tcl All is now in order: C:\Ruby Code>type hi.rb #!/usr/bin/env ruby puts "Hi, World!" Make sure you are able to execute the file: C:\Ruby Code>cacls hi.rb /g username:f Are you sure (Y/N)?y processed file: C:\Ruby Code\hi.rb Run the program by entering the program’s filename at the command prompt, with or without the file extension: C:\Ruby Code>hi Hi, World! To preserve these settings, you can add these commands to your autoexec.bat file, or set the environment variables by selecting Start → Control Panel → System, clicking the Advanced tab, and then clicking the Environment Variables button. Ruby’s Keywords Table 1 contains a list of Ruby’s keywords (also known as reserved words). Table 1. Ruby’s keywords Keyword Description BEGIN Code, enclosed in braces ({ }), to run before the program runs. 14 | Ruby Pocket Reference www.it-ebooks.info
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List