Ruby wizardry, p.25

Ruby Wizardry, page 25

 

Ruby Wizardry
Select Voice:
Brian (uk)
Emma (uk)  
Amy (uk)
Eric (us)
Ivy (us)
Joey (us)
Salli (us)  
Justin (us)
Jennifer (us)  
Kimberly (us)  
Kendra (us)
Russell (au)
Nicole (au)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

Larger Font   Reset Font Size   Smaller Font  

  Reflection/metaprogramming

  Remember when we talked about file I/O, we saw it was possible to write Ruby code that writes Ruby code? This means that Ruby has the ability to look at its own code and change it! The inward-looking part is called reflection, and the ability for Ruby to change its own programming is called metaprogramming. This is some of the hardest Ruby code to write, but if you’re feeling up to it, you can learn all about it from Paolo Perrotta’s book Metaprogramming Ruby.

  Debugging

  We talked a little bit about fixing errors in our code, but we didn’t talk about writing tests for it or debugging (that is, fixing) it in a systematic way. Writing tests to prove your code is correct and becoming good at debugging it are very important skills for any programmer to have. If you’re interested in learning more about both, you can read about the built-in Ruby testing library, MiniTest, in the Ruby documentation at http://ruby-doc.org/stdlib-1.9.3/libdoc/minitest/spec/rdoc/MiniTest/Spec.html. If you’re feeling particularly adventurous, you can read about my favorite testing library, RSpec, at http://rspec.info/.

  Threads and processes

  In all our Ruby programs, we really only did one thing at time: we’d set a variable and then use it, or maybe we’d iterate over an array and print each item to the screen. We never really did two things at exactly the same time. With Ruby threads and processes, it’s possible to do two things at once! As you might imagine, juggling multiple things at once is many times harder than handling just one process at a time, so learning to use Ruby threads and processes takes some practice. If you want to learn more, you can read Jesse Storimer’s Working with Ruby Threads (http://www.jstorimer.com/products/working-with-ruby-threads/). Careful—this one’s really advanced!

  Creating websites

  Finally, while we did talk about Ruby web servers like WEBrick, we didn’t talk much about creating entire websites with Ruby. You may have heard of Ruby on Rails (I mentioned it when describing Railscasts in Online and Multimedia), which is a big library of code made up of many gems that helps make writing websites with Ruby easier. It’s a good way to build websites and very popular, but sometimes newer Ruby programmers have trouble understanding all the things it does and decisions that went into making it. If you want to make websites with Ruby, you might want to start with a smaller, simpler program (and one of my favorites) called Sinatra. You can find it online at http://www.sinatrarb.com/.

  I admit it: I’ve been dragging my feet. I don’t want the book to end! But alas, I’ve dispensed all my Ruby wisdom. Now you know everything I know, plus you’ve got all the smarts and experience of the King, the Queen, Ruben, Scarlet, and all of their friends combined. I knew you could do it! I believed in you from the start. So even if the book has to end, at least it ends with me being right!

  When you close this book, I want you to do one thing: fire up your own personal Computing Contraption and write yourself a Ruby program. It can do anything you want, big or small, silly or serious. Don’t worry if it breaks! The only way we learn is by writing programs and breaking them and fixing them and making them better, so it’s perfectly okay if your program breaks or doesn’t do what you want at first. You’re writing stories and poems for a machine, and the biggest part of the adventure isn’t having a finished, perfectly working program—it’s all the crazy things that happen along the way.

  So go! Go write the best program you can, and have fun. I’ll be seeing you.

  Appendix A. Installing Ruby on Mac and Linux

  Installing on Mac

  New Macs ship with Ruby 2.0 already installed, so if you’re here, you’re likely using an older Mac that has Ruby 1.8.7. Not to worry! We’ll get you upgraded in a jiffy.

  Open up your terminal and type the following code. (The $ just shows you where to start typing—don’t type the $!) This will install a tool called RVM (Ruby Version Manager) as well as Ruby 2.0.

  $ curl -L https://get.rvm.io | bash -s stable --ruby=2.0.0 --auto-dotfiles

  Once you do this, you’ll see a whole bunch of text pop up to tell you that your computer is downloading Ruby. When it’s all done, close your terminal, reopen it, and enter ruby -v. You should see your computer print a response with ruby 2.0.0 in it!

  If your Ruby version still isn’t Ruby 2.0, you can try installing it using the Homebrew package manager. First, install Homebrew:

  $ ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/ install)"

  Once that command completes successfully, you can simply type this:

  $ brew install ruby

  At the time of this writing, Homebrew automatically installs Ruby 2.1.3. This is just a slightly newer version than Ruby 2.0, and it will work with the code examples in this book.

  Installing on Linux

  Open up your terminal and type the following code. (The $ just shows you where to start typing—don’t type the $!) This will install a tool called RVM (Ruby Version Manager) as well as Ruby 2.0.

  $ curl -L https://get.rvm.io | bash -s stable --ruby=2.0.0 --auto- dotfiles

  Once you do this, you’ll see a whole bunch of text pop up to tell you that your computer is downloading Ruby. When it’s all done, close your terminal, reopen it, and enter ruby -v. You should see your computer print a response with ruby 2.0.0 in it!

  If you get an error or your computer tells you that Ruby isn’t installed, grab your trusty adult and check out the Ruby installation page at https://www.ruby-lang.org/en/installation/. There may be a recent package designed especially for your version of Linux, and it may be easier to use that package to install Ruby, rather than using RVM. You can also ask your adult to go on IRC and get help from the folks in the #ruby channel.

  Appendix B. Troubleshooting

  When running your Ruby scripts or using IRB, you may run into some common errors. I’ve listed a few of them here, along with tips for fixing them!

  Errors Running Ruby Scripts

  There are two common errors that you might see when running Ruby scripts from the command line: Command Not Found and “no such file or directory.” Here are some suggestions for how to resolve them.

  Command Not Found

  If you’re running a Ruby script and you get some output that looks like this:

  $: command not found

  it probably means you accidentally typed a $ before your ruby command. I use the $ symbol to show you that you’re running a Ruby script from the command line with a filename (like ruby my_fancy_script.rb); you shouldn’t type the $ itself!

  No Such File or Directory

  If you get an error that looks like this:

  No such file or directory -- some_filename.rb (LoadError)

  it means you tried to run ruby some_filename.rb, but that file didn’t exist in the folder you’re currently in.

  To fix this, first make sure you’re in the folder where you saved your Ruby script. You can change from one folder to another using the cd command (for “change directory”). See Creating Your First Script for help using the cd command.

  If you’re in the correct folder and your command still gives you an error, double-check the spelling of your file! (I mistype the names of Ruby files all the time.)

  Errors Using IRB

  There are a few common errors that you might see when using IRB. Here’s how to fix them, along with some other handy tips for fixing typos and mistakes.

  Undefined Local Variable or Method

  If you try to call a method in IRB and get something like this:

  NameError: undefined local variable or method `some_method_name' for main:Object

  it means you tried to use a method that Ruby doesn’t know about. When you exit and restart IRB, Ruby forgets everything you were previously doing—so if you defined a method, exited IRB, and started it again, you’ll need to redefine that method to keep using it. (See Defining Your Own Methods if you need a refresher on how to define methods.) If your method is from a file, make sure you load that file using the command load 'your_file.rb', and if all else fails, double-check that you’ve spelled your method name correctly.

  Syntax Error

  If you get an error that looks like this:

  SyntaxError: (irb):1: syntax error, unexpected 'something_here'

  it means you wrote Ruby code that’s not quite right, and IRB doesn’t know what to do with it. Double-check your code for tiny errors, like typos, missing commas between elements in arrays, or missing hash rockets (=>) or colons in hashes.

  Can’t Convert nil into String

  If you get an error like this:

  TypeError: can't convert nil into String

  it means you tried to do something with one Ruby type (like a string, integer, or nil), but Ruby expected a different type. This often happens when something is nil and you don’t know it; if you see this error, try putsing out the values of all your variables to make sure each one is the type of thing (string, integer, array, and so on) that you expect! (See Getting to Know IRB for help with the puts command and A Bit More About Variables for a refresher on the types of variables.)

  You Were Saying . . . ?

  From time to time, you might see Ruby print something like this:

  ...?

  This means that Ruby expects you to “finish your thought.” Usually it means you pressed ENTER without closing a string, or maybe the last thing you typed was a + or - sign. All you need to do is finish that thought—complete the expression you started to type, close the string or array you opened, or whatever it is Ruby is waiting for—and you’ll be all set. For example:

  >> 1 + ...? 2 => 3

  If you have no idea what Ruby is waiting for, or you simply mistyped and want to start over, you can press CTRL-C to tell IRB not to wait for you. You’ll get your regular IRB prompt back and can continue from there. (For more about CTRL-C, see Investigating the Kingdom’s Web Server.)

  Clear the Screen

  Sometimes you’ll type a whole bunch in IRB and will want to clear the screen. You can do this in several ways, depending on which operating system you’re using. On a Mac, you can press ⌘-K or CTRL-L, or you can type system 'clear' into IRB and then press ENTER. If you’re using Linux, typing CTRL-L or entering system 'clear' should work. If you’re using Windows, typing CTRL-L or entering system 'cls' (not 'clear'!) should do the trick.

  Go Back to a Previous Command

  If at any point you want to go back to a previous command you typed into IRB, just hit the up arrow on your keyboard! This is great if you just cleared the screen and then realize you need to retype a command, or if you mistyped a command and want to try again without retyping everything you just did.

  Look It Up!

  Finally, if you ever see an error that you don’t know how to handle, go ahead and search for it on the Internet (after you get your local adult’s permission!). Everyone gets errors, so it’s likely that someone else has already figured out how to handle any error you might run into. Even the best programmers look up things they don’t know on a daily basis. The more comfortable you get hunting for answers when you’re stuck, the happier and more productive you’ll be when writing Ruby.

  Updates

  Visit http://nostarch.com/rubywizardry/ for updates, errata, and other information.

  More Smart Books for Curious Kids!

  JAVASCRIPT FOR KIDS

  A Playful Introduction to Programming

  by NICK MORGAN

  DECEMBER 2014, 336 PP., $34.95

  ISBN 978-1-59327-408-5

  full color

  LAUREN IPSUM

  A Story About Computer Science and Other Improbable Things

  by CARLOS BUENO

  DECEMBER 2014, 192 PP., $16.95

  ISBN 978-1-59327-574-7

  full color

  PYTHON FOR KIDS

  A Playful Introduction to Programming

  by JASON BRIGGS

  DECEMBER 2012, 344 PP., $34.95

  ISBN 978-1-59327-407-8

  full color

  LEARN TO PROGRAM WITH SCRATCH

  A Visual Introduction to Programming with Games, Art, Science, and Math

  by MAJED MARJI

  FEBRUARY 2014, 288 PP., $34.95

  ISBN 978-1-59327-543-3

  full color

  RAILS CRASH COURSE

  A No-Nonsense Guide to Rails Development

  by ANTHONY LEWIS

  OCTOBER 2014, 296 PP., $34.95

  ISBN 978-1-59327-572-3

  THE MANGA GUIDE™ TO DATABASES

  by MANA TAKAHASHI, SHOKO AZUMA, and TREND-PRO CO., LTD.

  JANUARY 2009, 224 PP., $19.95

  ISBN 978-1-59327-190-9

  800.420.7240 or 415.863.9900 | sales@nostarch.com | www.nostarch.com

  Index

  A note on the digital index

  A link in an index entry is displayed as the section title in which that entry appears. Because some sections have multiple index markers, it is not unusual for an entry to have several links to the same section. Clicking on any link will take you directly to the place in the text in which the marker appears.

  Symbols

  ! (not), His Majesty’s Flow Control, Improving flow_rate.rb with Fancier Logical Operators, You Know This!

  != (not equal to), Improving flow_rate.rb with Fancier Logical Operators

  #{}, for inserting variable value into string, Writing and Running Ruby Scripts, You Know This!

  $ (dollar sign), Putting on the Ruby Slippers, These Variable Errors Will Shock and Surprise You!, Command Not Found

  for global variables, These Variable Errors Will Shock and Surprise You!

  $home variable, Objects and Classes

  && (and), His Majesty’s Flow Control, Improving flow_rate.rb with Fancier Logical Operators, You Know This!

  () (parentheses), Defining Your Own Methods, Understanding Method Arguments

  * (asterisk), Ruby Operators, A Smallish Project for You, Splat Parameters, You Know This!

  as splat mark, Splat Parameters, You Know This!

  for multiplication, Ruby Operators, A Smallish Project for You

  , (comma), for separating key-value pairs, Hash in the Hashery

  .. (dots), in ranges, Rollicking Ranges, You Know This!

  ...?, for finishing your thought in IRB, Can’t Convert nil into String

  ./, for file location, Requiring Another File, You Know This!

  : (colon), Hash in the Hashery, Symbols!

  for hash, Hash in the Hashery

  for symbol, Symbols!

  ::, scope resolution operator, Looking Up Constants, You Know This!

  ; (semicolon), to end line of code, Creating Modules

  < (less than), His Majesty’s Flow Control, Inheritance and DRY Code, Inheritance and DRY Code

  for calling subclass, Inheritance and DRY Code

  for inheritance, Inheritance and DRY Code

  << (shovel operator), Order Up!

  <= (less than or equal to), His Majesty’s Flow Control

  = (equal sign), A Short Yarn, Understanding Method Arguments, Methods and Instance Variables

  for default parameters, Understanding Method Arguments

  in method name, Methods and Instance Variables

  == (equal to), Improving flow_rate.rb with Fancier Logical Operators

  => (hash rockets), When to Use IRB and When to Use a Text Editor, Hash in the Hashery, The Skinny on Symbols

  for IRB response, When to Use IRB and When to Use a Text Editor

  for symbol, The Skinny on Symbols

  > (greater than), His Majesty’s Flow Control

  >= (greater than or equal to), His Majesty’s Flow Control

  >>, and IRB prompt, When to Use IRB and When to Use a Text Editor

  ? (question mark), Crystal-Clear Conditionals, You Know This!

  and colon, as if/else alternative, Crystal-Clear Conditionals

  methods with, You Know This!

  @ (at sign), Creating Our First Class, Minstrel, Instance Variables

  for instance variables, Instance Variables

  @@, for class variables, Global Variables

  @name=, Creating Our First Class, Minstrel

  [] (square brackets), while Loops, You Know This!, You Know This!

  for arrays, while Loops, You Know This!

  for hash values, You Know This!

  n (newline), File Input and Output, Writing and Adding to Files

  _ (underscore), A Bit More About Variables, Symbols!

 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
Add Fast Bookmark
Load Fast Bookmark
Turn Navi On
Turn Navi On
Turn Navi On
Scroll Up
Turn Navi On
Scroll
Turn Navi On
183