INDEX

Symbols & Numbers = (assignment operator), 6 =begin, 4 & (ampersand), 166, 167 =begin , 345–346 && (and operator), 85, 93 =end, 4, 345–346 * (asterisk), 251–252, 260 == (equal-to operator), 56, 136 *?, 260 ===, 88, 92 @ (at sign), 23, 100 => (assoc operator), 141 @@ (class variables), 23, 100 =~, 250. See also regular expressions \ (line continuation character), 297 ! (exclamation mark) \B, 260 at end of methods, 131 \b , 260 as not operator, 85, 86, 93 \D , 260 != (not-equals operator), 86 \d, 260 // (delimiters), 250 \S, 260 > (greater-than sign), 56 \s, 260 # (hask mark), for comments, 4 \W, 260 #{}, in strings, 2 \w, 260 < (less-than sign), 56 ^ (caret), 251, 260. See also regular indicating descent, 17–18 expressions <=> (comparison operator), 54, 55, : (colon) 77, 207, 223 in case statements, 90 << instead of then, 84 append operator, 37, 63, 129 in symbols), 181 concatenation method, 130–131 :: (scope resolution operator), 30, with heredocs, 45 185, 193, 208–209, 330 and singletons, 109, 117 {} (curly brackets) <<-, with heredocs, 45 as delimiters, 161 <%%>. See Rails, tags in regular expressions, 260 <%=. See Rails, tags $ (dollar sign), 251–252, 260. See (), parentheses, also regular expressions; avoiding ambiguity, 85, 137, 162 variables optional, 2, 22 $`, 255. See also regular expressions in regular expressions, 260 $:, 202 and super, 18 $!, 141 %/, 35 $/ (record separator), 42 %d, 43 $', 255. See also regular expressions %f, 43 $~, 256. See also regular expressions %o, 43

The Book of Ruby © 2011 by Huw Collingbourne %p, 43 clear, 57 %Q, 35 clone, 53 %q, 35 collect, 159, 190 %r, 250. See also regular expressions compact, 57, 58 %s, 43 compact!, 57 %W, 46, 49 concatenating, 63–64 %w, 49 copying, 53 %x, 36, 43 creating, 48–50 . (period), 260 delete, 57 + (plus sign), 252, 260 delete_at, 57 +=, 23 each, 159 +?, 260 expressions in, 49 ? (question mark), 256, 260 of filenames, 49 ?..:, as shorthand for if..then..else, flatten, 57, 58 87, 269 flatten!, 57 [] (square brackets), 260 indexing, 52–53 | (vertical pipe), 260 iterators, 51–52, 159 || (or operator), 85, 93 length, 47 3rd Rail, 357 methods, 57–58 multidimensional, 50 A nested, 50 reverse, 57 accessor methods, 19 reverse!, 57 Ada, xviii sort, 57 Adobe Flex, 322 sort!, 57 alias, 199–200 sorting, 54–55 all_symbols, 190 of strings, 49 ambiguity, xix. See also testing for equality, 53–54 parentheses () treating hashes as, 63 avoiding, 123, 199 ASCII character codes, testing, 215 hashes and blocks, 162 assert, 293, 295 line breaks, 285, 296 assert_block, 295 ampersand (&), 166, 167 assert_equal, 292, 295 ancestors. See class hierarchy assert_in_delta, 295 and operator (&&), 85, 93 assert_instance_of, 295 Apache, 302, 358 assert_kind_of, 294 RadRails, 358 assert_match, 295 arguments assert_nil, 295 by reference, 129 assert_no_match, 295 default, 124 assert_not_equal, 295 passing, 134–135 assert_nothing_raised, 296 by value, 134 assert_nothing_thrown, 296 arrays, 47–48 assert_not_nil, 295 &, 57 assert_not_same, 295 -, 57 assert_operator, 296 <<, 57 assert_raise, 296 +, 57 assert_raises, 296 appending, 63–64 assert_respond_to, 296

362 INDEX The Book of Ruby © 2011 by Huw Collingbourne assert_same, 296 returning from methods, assert_send, 296 175–176 assert_thrown, 296 Ruby 1.9, 155 assignment operator (=), 6 scope of, 168, 177 assignments, 135–136 sorting with, 54 multiple, 133 blogs, 316–321 parallel, 133 books, on Ruby, 353–354 associative arrays. See hashes Boolean operators, 85–86, 93–94 assoc operator (=>), 141 negation, 86 asterisk (*), 251–252, 260 precedence, 93 at sign (@), 23, 100 side effects, 94 attr_accessor, 21, 327 break, 75, 90, 158–159 attributes, 20–23 breaking code over a line, 297. See attr_reader, 20, 182 also line breaks attr_writer, 20, 182 breakpoints, 289. See also debugging build_message, 296 B bytes, reading, 247 \B, 260 \b, 260 backquotes. See strings call, 187 backtrace, 150. See also exceptions camel case, xviii BasicObject, 29, 106, 142 capitalization. See strings =begin, 4 caret (^), 251, 260. See also regular begin..end, 73, 152 expressions =begin rdoc, 345–346 case sensitivity, 2 bindings, 334–336 case statements, 89 block_given?, 171 return values, 92 block parameters, 70, 157, 168, selectors, 91 170, 179 catch, 94–96, 152–153 blocks, 70, 155–156. See also fibers character codes. See strings {}, 70, 161 chomp, 42 call, 162 chop, 42 creating methods from, 332, 337 classes, 6 creating objects from, 162 descending from Object, 106 do..end, 70, 158 vs. modules, 192, 205 and for loops, 180 as objects, 104 and instance variables, 176–177 open, 30 and iterating arrays, 159–161 partial, 30–31 as iterators, 172–174 singleton, 108 and line breaks, 156–157 class_eval, 329–331 and local variables, 177–180 class hierarchy, 15–16 nested, 165 class methods, 97, 98, 122. See also parameters, 70, 157, 168, methods 170, 179 class_variable_get, 331–333 passing as named arguments, class variables, 23, 99 165–170 class_variables, 332 precedence, 170–171 class_variable_set, 331–333

INDEX 363 The Book of Ruby © 2011 by Huw Collingbourne clone, 60 default, 60 closures, 163–164. See also blocks default=, 60 collect, 76, 273. See also arrays; defined?, 179 Enumerable define_method, 188, 330, 337 colon (:) delete, 62 in case statements, 90 descendants, 15–16 instead of then, 84 destructors, 11 in symbols, 181 dictionaries. See hashes comments, 4 Digging Deeper in code examples, xvii arguments, passing, 134–135 multiline, 4 arrays, 63 single line, 4 assertions, 295–296 Comparable, 55, 206, 207 assignments, 135–136 comparison operator (<=>), 54, 55, begin..end, 152 77, 207, 223 blocks and closures, 175–180 conditional statements, 83. See Boolean operators, 93–94 also case statements; catch..throw, 94, 152–153 if modifiers debuggers, 297 constants, 90 each, 81 accessing with ::, 30, 207, 208 Enumerable, 76–81 inside classes, 30 equality, testing for, 136 const_get, 333 exceptions, 152–153 constructors extending objects, 210 initialize, 10–11, 104–105 freezing objects, 211, 342–343 new, 10–11, 104–105 hashes, 63 overriding, 104–105 heredocs, 45–46 const_set, 333 line breaks, 296–297 Controller, 305–307, 323 Marshal version numbers, copying files, 217–218. See also files 246–248 cp, 218 method accessibility, 114–116 curly brackets, {} modules, 205–210 as delimiters, 161 MVC, 322–323 in regular expressions, 260 Rails folders, 323 custom comparisons, 77 recursions, 224–226 regular expressions, 260–261 D Ruby frameworks, 324 scope resolution, 208–209 \D, 260 string literals, 46 \d, 260 superclasses, 25–30 %d, 43 symbols, 190, 261 databases, 358–359 threads, 278–281 data hiding, 128 unit testing, 295–296 debuggers, visual, 226, 297, 357–358 YAML, 237–238 debugging, 286 yield, 81 breakpoints, 289 directories, navigating in, 219. See with Ruby Debugger, 289 also files watchpoints, 290 Dir.foreach, 220 def, 5 Dir.getwd, 144

364 INDEX The Book of Ruby © 2011 by Huw Collingbourne do, 69, 156 eval, 186, 327. See also dynamic documenting Ruby. See RDoc programming do..end, 156, 158. See also blocks example programs, xix dollar sign ($), 251–252, 260. See exception hierarchy, 142 also regular expressions; exceptions, 140 variables and $!, 141 downto, 70–71 associating with variable dynamic programming, 188, 325 name, 141 adding methods, 337 backtrace, 150 adding methods to classes, 332 begin..end, omitting, 152 creating classes at runtime, 333 creating custom messages for, creating objects at runtime, 333 150–151 and embedded evaluation, 326 custom, raising, 151 eval, 327 displaying as strings, 148 freezing objects, 342 else, 145–146 monkey patching, 330 ensure, 144 removing methods, 337 Errno constants, 147 self-modifying programs, multiple, 142 326, 328 NoMethodError, 142 writing programs at runtime, 340 raise, 149 rescue, 140 E retry, 148 RuntimeError, 150 each, 68, 79, 159, 234 subclassing, 151 vs. for, 68 TypeError, 142, 342 and yield, 81 ZeroDivisionError, 141 ebooks, on Ruby, 355 exclamation mark (!) editors, Ruby, 357–358 at end of methods, 131 Eiffel, xviii, 6 as not operator, 85, 86, 93 else, 145. See also exceptions extend, 210 Embedded Ruby (ERb), 313, 314 encapsulation, 8, 128 breaking, 131, 333 F end, 5 %f, 43 =end, 4, 345–346 fibers ensure, 145. See also exceptions alive?, 276 Enumerable, 76–81, 206 and blocks, 275 collect, 76 dead, 276 include?, 76 FiberError, 276 including in a class, 79 parameters, 276 max, 76 resume, 275 min, 76, 78 and threads, 275 overriding methods, 80 yield, 275 equal?, 135, 136, 183 File methods, 98 equality, testing for, 136 files equal-to operator (==), 56, 136 backing up, 219 ERb (Embedded Ruby), 313, 314 closing, 214–216 Errno, 146–147. See also exceptions copying, 217

INDEX 365 The Book of Ruby © 2011 by Huw Collingbourne files (continued) H and directories, 217 Hansson, David Heinemeier, 316 eof, 215 hashes, 58 exist?, 217 copying, 60 foreach, 254, 258 creating, 58–59 handles, 215 and curly brackets, 161–162 modes, 214 has_key?, 62 opening, 214 has_value?, 62 processing using regular indexing into, 60 expressions, 258–259 items in reading/writing text, 215, 259 deleting, 62 saving data to YAML, 231 finding position of, 62 size of, 220 merging, 62 calculating, 219 methods, 62 sorting by, 222 order of elements, 60, 229 as a subclass of IO, 214 sort, 223 FileTest, 206 sorting, 61 FileUtils, 218 treating as arrays, 63 Fixnums, 136. See also integers hask mark (#), for comments, 4 flunk, 296 heredocs, 45–46 foreach, 213 HTML, tags, 309, 311. See also Rails for..in loops, 51 for loops, 67–70 and arrays, 71 I and blocks, 180 id2name, 186 and local variable scoping, 180 IDEs (integrated development envi- and multiple iterator ronments), 283, 357–358 arguments, 71 if..else, 84 and ranges, 69 if..elsif, 86 format strings, 43 if modifiers, 88–89 freeze, 211, 342–343 if..then, 4–5 frozen?, 211, 342 if..then..else, 84 functions, 157–158. See also methods include, 194. See also modules and module_function, 209 include?, 76, 88. See also Enumerable index, 62 G information hiding, 128 inheritance, 16 garbage collection, 11 initialize, 10–11 GC, 206 input and output. See IO (input and Gemfile, 319 output) Gems, Ruby, 300 inspect, 11–13 generate, 306 instance_eval, 329 getc, 216, 248 instance methods, 121–122 global variables, 5, 184. See also instance_variable_get, 103, 333 variables instance variables, 7, 23, 100 goto, 94 instance_variables, 197 instance_variable_set, 332

366 INDEX The Book of Ruby © 2011 by Huw Collingbourne integers loops, 73 object_id, 127 begin..end, 73 testing for equality, 136 each, 68 integrated development environ- executing at least once, 73 ments (IDEs), 283, for. See for loops 357–358 until, 29, 74 Interactive Ruby (IRB), 283–286 while, 72 invert, 62 IO (input and output) M class, 213 eof, 215 Maglev, 359 exceptions in, 144 main object, 9 foreach, 213 map, 273 getc, 215, 248 Marshal library, 239 gets, 2 compared to YAML, 240 print, 2 dump, 239 printf, 43, 221 file formats, 240 putc, 215 load, 239, 241 puts, 1 marshal_dump, 240, 243 readlines, 214 marshal_load, 241, 243 IRB (Interactive Ruby), 283–286 omitting variables, 240 IronRuby, 359 and singletons, 243 TypeError, 240 version numbers, 246–248 J MatchData, 254–255. See also regu- JRuby, 359 lar expressions Math, 193, 206, 207 K matrices, 64–65 Matsumoto, Yukihiro (Matz), xviii Kernel, 193, 206, 330 max, 76–80. See also Enumerable key, 62 messages, sending, 9, 64 keys, 59, 62 metaprogramming, 326. See also dynamic programming L method, 185, 187 lambda, 162–163 method_defined?, 189 lambdas, 161 method_missing, 339 less-than sign (<), 56 methods, 9, 97 indicating descent, 17–18 adding at runtime, 188, 337 , 302, 358 class, 97, 122 line breaks, 285, 296–297 vs. instance methods, 102 line continuation character (\), 297 vs. singleton methods, 105, Lisp, xviii, 163 116–118 load, 203 declaring, 5 LoadError, 202 default arguments, 124 LocalJumpError, 178 instance, 121 local variables. See variables vs. class methods, 102 loop, 75, 158 and message sending, 64

INDEX 367 The Book of Ruby © 2011 by Huw Collingbourne methods (continued) , 302, 358 missing, 338 monkey patching. See dynamic pro- module, 192 gramming nameless, 157–158 Mutex class, 272–275 naming, and capitalization, mv, 218 119–120 MVC. See Model-View- nested, 118–119 Controller (MVC) overriding, 110 MySQL, 300, 317, 349, 358 private, 111–113 configuring, 351 in descendant classes, 115 .dll file (Windows), 352 invading private methods, 116 errors, 319, 351–352 protected, 111–113, 114–116 no such file to load, 304, 351 public, 111–113, 115–116 aborted, 319 removing at runtime, 337 gem, installing, 351 returning multiple values, 124 installing, 350 returning values, 8, 123 username and password, 351 singleton, 105, 122 vs. class methods, 105, N 116–118 namespaces, 193. See also modules static, 97 nested methods, 118–119 migration, 318. See also Rails NetBeans, 358 min, 76–80. See also Enumerable mixins, 194–197. See also modules new, 10–11 , 358 potential problems with, 200–201 nil vs. multiple inheritance, 201 and array indexes, invalid, 48 mkdir, 218 displaying, 48, 251 Model, 322 nil?, 48 Model-View-Controller (MVC), NilClass, 48 301–302, 322–323 not-equals operator (!=), 86 Controller, 305–307, 323 not operator (!), 85, 86, 93 Model, 322 numbers, 3 View, 310–313, 322–323 module_eval, 329 module_function, 209 O modules, 191, 192 %o, 43 vs. classes, 192, 205 Object, 29, 106 and class variables, 197 methods, 185, 188 defined, 205 object_id, 39, 125, 126 and extend, 210 objects, 6–7 and functions, 209 creating at runtime, 333 included. See mixins extending, 210 including from files, 201 freezing, 211, 342–343 and instance methods, 192 identical, identifying, 136 and local variables, 195 inspecting, 11–13 as namespaces, 193 ObjectSpace, 206 predefined, 205–207 or operator (||), 85, 93 resolving name conflicts overriding methods, 110 with, 198

368 INDEX The Book of Ruby © 2011 by Huw Collingbourne P creating a View in, 310 database.yml, 317 p, 12 and embedded Ruby, 312, %p, 43 314–315 parallel assignments, 133 ERb files, 313–314, 322 parameters. See arguments folders, 323 parentheses, () generate, 306 and super, 18 generate controller, 306, 308, avoiding ambiguity, 85, 137, 162 309–310 optional, 2, 22 generating view methods in, 309 in regular expressions, 260 and HTML tags partial classes, 30–31 in Controller, 311 Pascal, 5, 68 in strings, 312–313 period (.), 260 installating, 300–301 PI, 207 and instance variables, 311–312 plus sign (+), 252, 260 migration, 318 polymorphism, 9 and MySQL, configuring, 317 PostgreSQL, 359 vs. other frameworks, 324 Precision, 206 partials, 318 private methods, 111–113 passing data from Controller to in descendant classes, 115–116 View, 311 invading, 116 pluralization, 322 Proc, 162–163 and raw, 313 new, 162 and render, 306, 309, 311 in Ruby 1.8, 163 .rhtml, 314, 322 in Ruby 1.9, 163 routes, in Rails 3, 307 Process, 206 running server, 320 procs, 161. See blocks scaffolding, 317–318 properties, 21. See also attributes tags, 312, 313 protected methods, 111–113, templates, 323 114–116 updating, 301 public methods, 111–113, 115–116 Rails 2, commands, 303, 316 generate controller, 305, 310 Q generate scaffold, 317 server, 304, 307, 320 %Q, 35 Rails 3, commands, 303, 316 %q, 35 script/generate controller, question mark (?), 256, 260 305, 310 script/generate scaffold, 317 R script/server, 304, 307, 320 %r, 250. See also regular expressions raise, 149–151. See also exceptions Rails rake, 318 and ApplicationController, 308 Ramaze, 324 blog application in, 316 ranges, 43–44 and class hierarchy, 312–313 RDoc, 345–347 “configuration by convention” adding title with, 347 approach, 306, 312 excluding comments from, 347 formatting, 347

INDEX 369 The Book of Ruby © 2011 by Huw Collingbourne readlines, 214 downloading, xx, 359 receiver objects, 64 ebooks on, 355 modifying, 130–131 editors, 357–358 record separator ($/), 42 frameworks, 324. See also Rails recursions, 219–222, 224–226 IDEs, 357–358 regular expressions (Regexp), 249 implementations, xviii, 359 captures, 253, 255 library documentation, xxi custom delimiters, 250 one-click Installer, 288 elements, 260–261 running Ruby programs, xxi *, 251–252, 260 , 357–358 ^ , 251, 260 style conventions, xviii–xix $, 251–252, 260 websites on, 355 $`, 255 Ruby 1.8, xviii, xxi $~, 256 Ruby 1.9 $', 255 BasicObject, 29, 106 // (delimiters), 250 binding, 336 %r, 250 block parameters, 168, 179 +, 252 class variable scope, 335 ?, 256 deadlocks, 272 greedy, 256 displaying arrays, 52 groups, 253–254 fibers, 275 match, 254–255 getc, 248 MatchData, 254–255 handling Ruby 1.8 matching, 250–253 compatibility, 216 post_match, 255–256 hash order, 60, 76, 78 pre_match, 255–256 indexing a hash, 62 processing paths, 256 instance_variables, 197 quantifiers, 251 local variables, 179 quick reference, 260 Marshal version numbers, samples of, 260 246–248 and strings, 256 nil, 48, 251 symbols, 261 not, 94 to_a, 255 print, 48, 52 remove_method, 189, 337 puts, 48, 52 require, 201 regular expressions, symbols, 261 vs. load, 203 require, 202 problems, 202 require_relative, 202 require_relative, 202 singleton_methods, 110 rescue, 140–144. See also exceptions sorting symbols, 190 respond_to?, 108 string indexing, 39–41 retry, 148–149 then syntax, unsupported, 84, 90 return, 8, 123 .pass, 279 RHTML, 314, 322. See also Rails threads, 265 rm, 218 priorities, 270, 272 , 359 statuses, 266–267 Ruby to_s, with exceptions, 148 books on, 353–354 Ruby 2.0, xviii defined, xviii Ruby Gems, 300

370 INDEX The Book of Ruby © 2011 by Huw Collingbourne .rb, 288 SQLite3, installaing, 301 Ruby In Steel, 226, 297, 358. See also SQL Server Express, 359 IDEs (integrated develop- sqrt, 207 ment environments) square brackets, [], 260 RubyMine, 358 static methods. See class methods . See Rails static variables. See class variables RUBYOPT, 288 string literals, 46 RUBY_VERSION, 216 strings. See also regular expressions =~, 256 S assignments, 38–39 backquotes, 36, 49 \S, 260 and capitalize method, 39, \s, 260 41, 160 %s, 43 capitalize! method, 160–161 saving data. See Marshal and character codes, 37 library; YAML and chomp method, 42 scaffolding, 317. See also Rails and chop method, 42 scope resolution operator (::), 30, chr, 161 185, 193, 208–209, 330 concatenation, 37 scopes, 5–6 delimiters, user-defined, 35 send, 116, 332, 336 serialization, 240. See also Marshal double-quoted, 2, 33–35 downcase, 41 library; YAML each_byte, 161 server ports, 304 and embedded evaluation, sets, 65 2–3, 33 adding new values to, 65 format, 43 merging, 65 formatting, 221 sorting, 66 gsub, 258 testing for equality, 66 indexing into, 39–41 setup. See unit testing and insert method, 41 Signal, 206 length, 41 , 324 matching singleton classes, 108–110 methods of String class, 256 singleton class methods, 116–118 regular expressions, 250–253 singleton methods, 105–108, 122. and ord method, 216, 247 See also methods record separator ($/), 42 singleton_methods, 108, 110 and reverse method, 41 singletons and reverse! method, 130 and Marshal library, 243–245 scan, 256–257 saving, and reloading, 242 single-quoted, 34 and YAML, 242–243 slice, 257 sleep, 265 split, 41, 160, 257 , xviii, 6, 9, 128 squeeze, 41 sort, 61, 77, 223 sub, 258 for this book, xxi swapcase, 41 SQLite, 301, 359 and to_f method, 3, 216 no such file to load, 304 and to_s method, 13 and Rails, 300 upcase, 41

INDEX 371 The Book of Ruby © 2011 by Huw Collingbourne super, 18, 23, 27, 104 U superclasses, 17–18, 25–30 ubygems.rb, 288 symbols, 20, 181 undef_method, 338 defined, 181, 190 unit testing, 292 and dynamic programming, 188 assertions available, 295–296 evaluating, 186 setup, 294 and regular expressions, 261 teardown, 294 scope of, 184 TestCase, 292 sorting, 190 unless modifiers, 88–89 vs. strings, 182 unless tests, 88 uniqueness of, 182 until loops, 74–75. See also loops usefulness of, 188–189 upto, 70–71 and variables, 186

T V variables teardown, 294. See also unit testing class, 23 TestCase, 292. See also unit testing class instance, 102 TextMate, 358 class methods, 99 then, 4–5 global, 5, 184 threads, 263 instance, 7, 100 creating, 264 local, 5 deadlocks, 272 in modules, 195 ensuring execution of, 268–269 static, 99 and fibers, 275 vectors, 64–65 green, 265 vertical pipe (|), 260 and join method, 268 View, 310–313, 322–323 main, 266, 271 mutexes, 272–275 native, 265 W and pass method, 269, 278–281 \W, 260 and preemptive multitasking, 265 \w, 260 priorities, 269 %W, 46, 49 problems, 270 %w, 49 setting, 270 Waves, 324 running, 264–265 WEBrick, 302 , 281 running, 304 and sleep method, 268 website, 358 statuses, 266–268 web servers, 302, 358 and stop method, 272, 281 websites, on Ruby, 355 synchronizing, 273 when, 89–91, 92 time-slicing, 265 while loops, 72–74 throw, 94–96, 152–153 while modifiers, 72–73, 89 times, 156, 178 word counter, 258 to_a, 44, 255 to_f, 3, 216 X to_s, 13, 22, 148 %x, 36, 43 to_yaml, 228

372 INDEX The Book of Ruby © 2011 by Huw Collingbourne Y y, 229 YAML, 227 adventure game, 236 arrays, 230, 237–238 documents, 228, 233 and dump method, 231 elements, 228 formats, 237 and hashes, 237 and indentation, 231, 238 and load_documents method, 234 loading data, 231, 234 and nested sequences, 231 omitting variables, 232–233 reconstructing complex data, 236 saving data, 231, 234 and singletons, 242–243 to_yaml, 228 to_yaml_properties, 232 y, 229 YARV (Yet Another Ruby Virtual- machine), 265 yield, 81, 164. See also blocks

INDEX 373 The Book of Ruby © 2011 by Huw Collingbourne