├── .gitattributes ├── CONTRIBUTING.md └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | *.md whitespace=trailing-space,tab-in-indent 2 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | * [Fork](https://help.github.com/articles/fork-a-repo) the project on GitHub. 2 | * Make your feature addition or bug fix in a feature branch. (Include a description of your changes) 3 | * Push your feature branch to GitHub. 4 | * Send a [Pull Request](https://help.github.com/articles/using-pull-requests). -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Prelude 2 | 3 | > Role models are important.
4 | > -- Officer Alex J. Murphy / RoboCop 5 | 6 | One thing has always bothered me as a Ruby developer - Python developers have a 7 | great programming style reference 8 | ([PEP-8][]) and we never got an official 9 | guide, documenting Ruby coding style and best practices. And I do believe that 10 | style matters. I also believe that a great hacker community, such as Ruby has, 11 | should be quite capable of producing this coveted document. 12 | 13 | This guide started its life as our internal company Ruby coding guidelines 14 | (written by yours truly). At some point I decided that the work I was doing 15 | might be interesting to members of the Ruby community in general and that the 16 | world had little need for another internal company guideline. But the world 17 | could certainly benefit from a community-driven and community-sanctioned set of 18 | practices, idioms and style prescriptions for Ruby programming. 19 | 20 | Since the inception of the guide I've received a lot of feedback from members of 21 | the exceptional Ruby community around the world. Thanks for all the suggestions 22 | and the support! Together we can make a resource beneficial to each and every 23 | Ruby developer out there. 24 | 25 | By the way, if you're into Rails you might want to check out the complementary 26 | [Ruby on Rails Style Guide][rails-style-guide]. 27 | 28 | # The Ruby Style Guide 29 | 30 | This Ruby style guide recommends best practices so that real-world Ruby 31 | programmers can write code that can be maintained by other real-world Ruby 32 | programmers. A style guide that reflects real-world usage gets used, and a style 33 | guide that holds to an ideal that has been rejected by the people it is supposed 34 | to help risks not getting used at all – no matter how good it is. 35 | 36 | The guide is separated into several sections of related rules. I've tried to add 37 | the rationale behind the rules (if it's omitted I've assumed it's pretty 38 | obvious). 39 | 40 | I didn't come up with all the rules out of nowhere - they are mostly 41 | based on my extensive career as a professional software engineer, 42 | feedback and suggestions from members of the Ruby community and 43 | various highly regarded Ruby programming resources, such as 44 | ["Programming Ruby 1.9"][pickaxe] and 45 | ["The Ruby Programming Language"][trpl]. 46 | 47 | There are some areas in which there is no clear consensus in the Ruby community 48 | regarding a particular style (like string literal quoting, spacing inside hash 49 | literals, dot position in multi-line method chaining, etc.). In such scenarios 50 | all popular styles are acknowledged and it's up to you to pick one and apply it 51 | consistently. 52 | 53 | This style guide evolves over time as additional conventions are 54 | identified and past conventions are rendered obsolete by changes in 55 | Ruby itself. 56 | 57 | Many projects have their own coding style guidelines (often derived 58 | from this guide). In the event of any conflicts, such 59 | project-specific guides take precedence for that project. 60 | 61 | You can generate a PDF or an HTML copy of this guide using 62 | [Transmuter][]. 63 | 64 | [RuboCop][] is a code analyzer, based on this 65 | style guide. 66 | 67 | Translations of the guide are available in the following languages: 68 | 69 | * [Chinese Simplified](https://github.com/JuanitoFatas/ruby-style-guide/blob/master/README-zhCN.md) 70 | * [Chinese Traditional](https://github.com/JuanitoFatas/ruby-style-guide/blob/master/README-zhTW.md) 71 | * [French](https://github.com/porecreat/ruby-style-guide/blob/master/README-frFR.md) 72 | * [German](https://github.com/arbox/ruby-style-guide/blob/master/README-deDE.md) 73 | * [Japanese](https://github.com/fortissimo1997/ruby-style-guide/blob/japanese/README.ja.md) 74 | * [Korean](https://github.com/dalzony/ruby-style-guide/blob/master/README-koKR.md) 75 | * [Portuguese](https://github.com/rubensmabueno/ruby-style-guide/blob/master/README-PT-BR.md) 76 | * [Russian](https://github.com/arbox/ruby-style-guide/blob/master/README-ruRU.md) 77 | * [Spanish](https://github.com/alemohamad/ruby-style-guide/blob/master/README-esLA.md) 78 | * [Vietnamese](https://github.com/scrum2b/ruby-style-guide/blob/master/README-viVN.md) 79 | 80 | ## Table of Contents 81 | 82 | * [Source Code Layout](#source-code-layout) 83 | * [Syntax](#syntax) 84 | * [Naming](#naming) 85 | * [Comments](#comments) 86 | * [Comment Annotations](#comment-annotations) 87 | * [Classes](#classes--modules) 88 | * [Exceptions](#exceptions) 89 | * [Collections](#collections) 90 | * [Strings](#strings) 91 | * [Regular Expressions](#regular-expressions) 92 | * [Percent Literals](#percent-literals) 93 | * [Metaprogramming](#metaprogramming) 94 | * [Misc](#misc) 95 | * [Tools](#tools) 96 | 97 | ## Source Code Layout 98 | 99 | > Nearly everybody is convinced that every style but their own is 100 | > ugly and unreadable. Leave out the "but their own" and they're 101 | > probably right...
102 | > -- Jerry Coffin (on indentation) 103 | 104 | * 105 | Use `UTF-8` as the source file encoding. 106 | [[link](#utf-8)] 107 | 108 | * 109 | Use two **spaces** per indentation level (aka soft tabs). No hard tabs. 110 | [[link](#spaces-indentation)] 111 | 112 | ```Ruby 113 | # bad - four spaces 114 | def some_method 115 | do_something 116 | end 117 | 118 | # good 119 | def some_method 120 | do_something 121 | end 122 | ``` 123 | 124 | * 125 | Use Unix-style line endings. (*BSD/Solaris/Linux/OS X users are covered by 126 | default, Windows users have to be extra careful.) 127 | [[link](#crlf)] 128 | 129 | * If you're using Git you might want to add the following 130 | configuration setting to protect your project from Windows line 131 | endings creeping in: 132 | 133 | ```bash 134 | $ git config --global core.autocrlf true 135 | ``` 136 | 137 | * 138 | Don't use `;` to separate statements and expressions. As a corollary - use one 139 | expression per line. 140 | [[link](#no-semicolon)] 141 | 142 | ```Ruby 143 | # bad 144 | puts 'foobar'; # superfluous semicolon 145 | 146 | puts 'foo'; puts 'bar' # two expressions on the same line 147 | 148 | # good 149 | puts 'foobar' 150 | 151 | puts 'foo' 152 | puts 'bar' 153 | 154 | puts 'foo', 'bar' # this applies to puts in particular 155 | ``` 156 | 157 | * 158 | Prefer a single-line format for class definitions with no body. 159 | [[link](#single-line-classes)] 160 | 161 | ```Ruby 162 | # bad 163 | class FooError < StandardError 164 | end 165 | 166 | # okish 167 | class FooError < StandardError; end 168 | 169 | # good 170 | FooError = Class.new(StandardError) 171 | ``` 172 | 173 | * 174 | Avoid single-line methods. Although they are somewhat popular in the wild, 175 | there are a few peculiarities about their definition syntax that make their 176 | use undesirable. At any rate - there should be no more than one expression in 177 | a single-line method. 178 | [[link](#no-single-line-methods)] 179 | 180 | ```Ruby 181 | # bad 182 | def too_much; something; something_else; end 183 | 184 | # okish - notice that the first ; is required 185 | def no_braces_method; body end 186 | 187 | # okish - notice that the second ; is optional 188 | def no_braces_method; body; end 189 | 190 | # okish - valid syntax, but no ; makes it kind of hard to read 191 | def some_method() body end 192 | 193 | # good 194 | def some_method 195 | body 196 | end 197 | ``` 198 | 199 | One exception to the rule are empty-body methods. 200 | 201 | ```Ruby 202 | # good 203 | def no_op; end 204 | ``` 205 | 206 | * 207 | Use spaces around operators, after commas, colons and semicolons, around `{` 208 | and before `}`. Whitespace might be (mostly) irrelevant to the Ruby 209 | interpreter, but its proper use is the key to writing easily readable code. 210 | [[link](#spaces-operators)] 211 | 212 | ```Ruby 213 | sum = 1 + 2 214 | a, b = 1, 2 215 | [1, 2, 3].each { |e| puts e } 216 | class FooError < StandardError; end 217 | ``` 218 | 219 | The only exception, regarding operators, is the exponent operator: 220 | 221 | ```Ruby 222 | # bad 223 | e = M * c ** 2 224 | 225 | # good 226 | e = M * c**2 227 | ``` 228 | 229 | `{` and `}` deserve a bit of clarification, since they are used 230 | for block and hash literals, as well as embedded expressions in 231 | strings. For hash literals two styles are considered acceptable. 232 | 233 | ```Ruby 234 | # good - space after { and before } 235 | { one: 1, two: 2 } 236 | 237 | # good - no space after { and before } 238 | {one: 1, two: 2} 239 | ``` 240 | 241 | The first variant is slightly more readable (and arguably more 242 | popular in the Ruby community in general). The second variant has 243 | the advantage of adding visual difference between block and hash 244 | literals. Whichever one you pick - apply it consistently. 245 | 246 | As far as embedded expressions go, there are also two acceptable 247 | options: 248 | 249 | ```Ruby 250 | # good - no spaces 251 | "string#{expr}" 252 | 253 | # ok - arguably more readable 254 | "string#{ expr }" 255 | ``` 256 | 257 | The first style is extremely more popular and you're generally 258 | advised to stick with it. The second, on the other hand, is 259 | (arguably) a bit more readable. As with hashes - pick one style 260 | and apply it consistently. 261 | 262 | * 263 | No spaces after `(`, `[` or before `]`, `)`. 264 | [[link](#no-spaces-braces)] 265 | 266 | ```Ruby 267 | some(arg).other 268 | [1, 2, 3].size 269 | ``` 270 | 271 | * 272 | No space after `!`. 273 | [[link](#no-space-bang)] 274 | 275 | ```Ruby 276 | # bad 277 | ! something 278 | 279 | # good 280 | !something 281 | ``` 282 | 283 | * 284 | No space inside range literals. 285 | [[link](#no-space-inside-range-literals)] 286 | 287 | ```Ruby 288 | # bad 289 | 1 .. 3 290 | 'a' ... 'z' 291 | 292 | # good 293 | 1..3 294 | 'a'...'z' 295 | ``` 296 | 297 | * 298 | Indent `when` as deep as `case`. I know that many would disagree 299 | with this one, but it's the style established in both "The Ruby 300 | Programming Language" and "Programming Ruby". 301 | [[link](#indent-when-to-case)] 302 | 303 | ```Ruby 304 | # bad 305 | case 306 | when song.name == 'Misty' 307 | puts 'Not again!' 308 | when song.duration > 120 309 | puts 'Too long!' 310 | when Time.now.hour > 21 311 | puts "It's too late" 312 | else 313 | song.play 314 | end 315 | 316 | # good 317 | case 318 | when song.name == 'Misty' 319 | puts 'Not again!' 320 | when song.duration > 120 321 | puts 'Too long!' 322 | when Time.now.hour > 21 323 | puts "It's too late" 324 | else 325 | song.play 326 | end 327 | ``` 328 | 329 | * 330 | When assigning the result of a conditional expression to a variable, 331 | preserve the usual alignment of its branches. 332 | [[link](#indent-conditional-assignment)] 333 | 334 | ```Ruby 335 | # bad - pretty convoluted 336 | kind = case year 337 | when 1850..1889 then 'Blues' 338 | when 1890..1909 then 'Ragtime' 339 | when 1910..1929 then 'New Orleans Jazz' 340 | when 1930..1939 then 'Swing' 341 | when 1940..1950 then 'Bebop' 342 | else 'Jazz' 343 | end 344 | 345 | result = if some_cond 346 | calc_something 347 | else 348 | calc_something_else 349 | end 350 | 351 | # good - it's apparent what's going on 352 | kind = case year 353 | when 1850..1889 then 'Blues' 354 | when 1890..1909 then 'Ragtime' 355 | when 1910..1929 then 'New Orleans Jazz' 356 | when 1930..1939 then 'Swing' 357 | when 1940..1950 then 'Bebop' 358 | else 'Jazz' 359 | end 360 | 361 | result = if some_cond 362 | calc_something 363 | else 364 | calc_something_else 365 | end 366 | 367 | # good (and a bit more width efficient) 368 | kind = 369 | case year 370 | when 1850..1889 then 'Blues' 371 | when 1890..1909 then 'Ragtime' 372 | when 1910..1929 then 'New Orleans Jazz' 373 | when 1930..1939 then 'Swing' 374 | when 1940..1950 then 'Bebop' 375 | else 'Jazz' 376 | end 377 | 378 | result = 379 | if some_cond 380 | calc_something 381 | else 382 | calc_something_else 383 | end 384 | ``` 385 | 386 | * 387 | Use empty lines between method definitions and also to break up a method 388 | into logical paragraphs internally. 389 | [[link](#empty-lines-between-methods)] 390 | 391 | ```Ruby 392 | def some_method 393 | data = initialize(options) 394 | 395 | data.manipulate! 396 | 397 | data.result 398 | end 399 | 400 | def some_method 401 | result 402 | end 403 | ``` 404 | 405 | * 406 | Avoid comma after the last parameter in a method call, especially when the 407 | parameters are not on separate lines. 408 | [[link](#no-trailing-params-comma)] 409 | 410 | ```Ruby 411 | # bad - easier to move/add/remove parameters, but still not preferred 412 | some_method( 413 | size, 414 | count, 415 | color, 416 | ) 417 | 418 | # bad 419 | some_method(size, count, color, ) 420 | 421 | # good 422 | some_method(size, count, color) 423 | ``` 424 | 425 | * 426 | Use spaces around the `=` operator when assigning default values to method 427 | parameters: 428 | [[link](#spaces-around-equals)] 429 | 430 | ```Ruby 431 | # bad 432 | def some_method(arg1=:default, arg2=nil, arg3=[]) 433 | # do something... 434 | end 435 | 436 | # good 437 | def some_method(arg1 = :default, arg2 = nil, arg3 = []) 438 | # do something... 439 | end 440 | ``` 441 | 442 | While several Ruby books suggest the first style, the second is much more 443 | prominent in practice (and arguably a bit more readable). 444 | 445 | * 446 | Avoid line continuation `\` where not required. In practice, avoid using 447 | line continuations for anything but string concatenation. 448 | [[link](#no-trailing-backslash)] 449 | 450 | ```Ruby 451 | # bad 452 | result = 1 - \ 453 | 2 454 | 455 | # good (but still ugly as hell) 456 | result = 1 \ 457 | - 2 458 | 459 | long_string = 'First part of the long string' \ 460 | ' and second part of the long string' 461 | ``` 462 | 463 | * 464 | Adopt a consistent multi-line method chaining style. There are two 465 | popular styles in the Ruby community, both of which are considered 466 | good - leading `.` (Option A) and trailing `.` (Option B). 467 | [[link](#consistent-multi-line-chains)] 468 | 469 | * **(Option A)** When continuing a chained method invocation on 470 | another line keep the `.` on the second line. 471 | 472 | ```Ruby 473 | # bad - need to consult first line to understand second line 474 | one.two.three. 475 | four 476 | 477 | # good - it's immediately clear what's going on the second line 478 | one.two.three 479 | .four 480 | ``` 481 | 482 | * **(Option B)** When continuing a chained method invocation on another line, 483 | include the `.` on the first line to indicate that the 484 | expression continues. 485 | 486 | ```Ruby 487 | # bad - need to read ahead to the second line to know that the chain continues 488 | one.two.three 489 | .four 490 | 491 | # good - it's immediately clear that the expression continues beyond the first line 492 | one.two.three. 493 | four 494 | ``` 495 | 496 | A discussion on the merits of both alternative styles can be found 497 | [here](https://github.com/bbatsov/ruby-style-guide/pull/176). 498 | 499 | * 500 | Align the parameters of a method call if they span more than one 501 | line. When aligning parameters is not appropriate due to line-length 502 | constraints, single indent for the lines after the first is also 503 | acceptable. 504 | [[link](#no-double-indent)] 505 | 506 | ```Ruby 507 | # starting point (line is too long) 508 | def send_mail(source) 509 | Mailer.deliver(to: 'bob@example.com', from: 'us@example.com', subject: 'Important message', body: source.text) 510 | end 511 | 512 | # bad (double indent) 513 | def send_mail(source) 514 | Mailer.deliver( 515 | to: 'bob@example.com', 516 | from: 'us@example.com', 517 | subject: 'Important message', 518 | body: source.text) 519 | end 520 | 521 | # good 522 | def send_mail(source) 523 | Mailer.deliver(to: 'bob@example.com', 524 | from: 'us@example.com', 525 | subject: 'Important message', 526 | body: source.text) 527 | end 528 | 529 | # good (normal indent) 530 | def send_mail(source) 531 | Mailer.deliver( 532 | to: 'bob@example.com', 533 | from: 'us@example.com', 534 | subject: 'Important message', 535 | body: source.text 536 | ) 537 | end 538 | ``` 539 | 540 | * 541 | Align the elements of array literals spanning multiple lines. 542 | [[link](#align-multiline-arrays)] 543 | 544 | ```Ruby 545 | # bad - single indent 546 | menu_item = ['Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 547 | 'Baked beans', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam'] 548 | 549 | # good 550 | menu_item = [ 551 | 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 552 | 'Baked beans', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam' 553 | ] 554 | 555 | # good 556 | menu_item = 557 | ['Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam', 558 | 'Baked beans', 'Spam', 'Spam', 'Spam', 'Spam', 'Spam'] 559 | ``` 560 | 561 | * 562 | Add underscores to large numeric literals to improve their readability. 563 | [[link](#underscores-in-numerics)] 564 | 565 | ```Ruby 566 | # bad - how many 0s are there? 567 | num = 1000000 568 | 569 | # good - much easier to parse for the human brain 570 | num = 1_000_000 571 | ``` 572 | 573 | * 574 | Use RDoc and its conventions for API documentation. Don't put an 575 | empty line between the comment block and the `def`. 576 | [[link](#rdoc-conventions)] 577 | 578 | * 579 | Limit lines to 80 characters. 580 | [[link](#80-character-limits)] 581 | 582 | * 583 | Avoid trailing whitespace. 584 | [[link](#no-trailing-whitespace)] 585 | 586 | * 587 | End each file with a newline. 588 | [[link](#newline-eof)] 589 | 590 | * 591 | Don't use block comments. They cannot be preceded by whitespace and are not 592 | as easy to spot as regular comments. 593 | [[link](#no-block-comments)] 594 | 595 | ```Ruby 596 | # bad 597 | =begin 598 | comment line 599 | another comment line 600 | =end 601 | 602 | # good 603 | # comment line 604 | # another comment line 605 | ``` 606 | 607 | ## Syntax 608 | 609 | * 610 | Use `::` only to reference constants(this includes classes and 611 | modules) and constructors (like `Array()` or `Nokogiri::HTML()`). 612 | Do not use `::` for regular method invocation. 613 | [[link](#double-colons)] 614 | 615 | ```Ruby 616 | # bad 617 | SomeClass::some_method 618 | some_object::some_method 619 | 620 | # good 621 | SomeClass.some_method 622 | some_object.some_method 623 | SomeModule::SomeClass::SOME_CONST 624 | SomeModule::SomeClass() 625 | ``` 626 | 627 | * 628 | Use `def` with parentheses when there are parameters. Omit the 629 | parentheses when the method doesn't accept any parameters. 630 | [[link](#method-parens)] 631 | 632 | ```Ruby 633 | # bad 634 | def some_method() 635 | # body omitted 636 | end 637 | 638 | # good 639 | def some_method 640 | # body omitted 641 | end 642 | 643 | # bad 644 | def some_method_with_parameters param1, param2 645 | # body omitted 646 | end 647 | 648 | # good 649 | def some_method_with_parameters(param1, param2) 650 | # body omitted 651 | end 652 | ``` 653 | 654 | * 655 | Do not use `for`, unless you know exactly why. Most of the time iterators 656 | should be used instead. `for` is implemented in terms of `each` (so 657 | you're adding a level of indirection), but with a twist - `for` 658 | doesn't introduce a new scope (unlike `each`) and variables defined 659 | in its block will be visible outside it. 660 | [[link](#no-for-loops)] 661 | 662 | ```Ruby 663 | arr = [1, 2, 3] 664 | 665 | # bad 666 | for elem in arr do 667 | puts elem 668 | end 669 | 670 | # note that elem is accessible outside of the for loop 671 | elem # => 3 672 | 673 | # good 674 | arr.each { |elem| puts elem } 675 | 676 | # elem is not accessible outside each's block 677 | elem # => NameError: undefined local variable or method `elem' 678 | ``` 679 | 680 | * 681 | Do not use `then` for multi-line `if/unless`. 682 | [[link](#no-then)] 683 | 684 | ```Ruby 685 | # bad 686 | if some_condition then 687 | # body omitted 688 | end 689 | 690 | # good 691 | if some_condition 692 | # body omitted 693 | end 694 | ``` 695 | 696 | * 697 | Always put the condition on the same line as the `if`/`unless` in a 698 | multi-line conditional. 699 | [[link](#same-line-condition)] 700 | 701 | ```Ruby 702 | # bad 703 | if 704 | some_condition 705 | do_something 706 | do_something_else 707 | end 708 | 709 | # good 710 | if some_condition 711 | do_something 712 | do_something_else 713 | end 714 | ``` 715 | 716 | * 717 | Favor the ternary operator(`?:`) over `if/then/else/end` constructs. 718 | It's more common and obviously more concise. 719 | [[link](#ternary-operator)] 720 | 721 | ```Ruby 722 | # bad 723 | result = if some_condition then something else something_else end 724 | 725 | # good 726 | result = some_condition ? something : something_else 727 | ``` 728 | 729 | * 730 | Use one expression per branch in a ternary operator. This 731 | also means that ternary operators must not be nested. Prefer 732 | `if/else` constructs in these cases. 733 | [[link](#no-nested-ternary)] 734 | 735 | ```Ruby 736 | # bad 737 | some_condition ? (nested_condition ? nested_something : nested_something_else) : something_else 738 | 739 | # good 740 | if some_condition 741 | nested_condition ? nested_something : nested_something_else 742 | else 743 | something_else 744 | end 745 | ``` 746 | 747 | * 748 | Do not use `if x; ...`. Use the ternary 749 | operator instead. 750 | [[link](#no-semicolon-ifs)] 751 | 752 | ```Ruby 753 | # bad 754 | result = if some_condition; something else something_else end 755 | 756 | # good 757 | result = some_condition ? something : something_else 758 | ``` 759 | 760 | * 761 | Leverage the fact that `if` and `case` are expressions which return a 762 | result. 763 | [[link](#use-if-case-returns)] 764 | 765 | ```Ruby 766 | # bad 767 | if condition 768 | result = x 769 | else 770 | result = y 771 | end 772 | 773 | # good 774 | result = 775 | if condition 776 | x 777 | else 778 | y 779 | end 780 | ``` 781 | 782 | * 783 | Use `when x then ...` for one-line cases. The alternative syntax `when x: 784 | ...` has been removed as of Ruby 1.9. 785 | [[link](#one-line-cases)] 786 | 787 | * 788 | Do not use `when x; ...`. See the previous rule. 789 | [[link](#no-when-semicolons)] 790 | 791 | * 792 | Use `!` instead of `not`. 793 | [[link](#bang-not-not)] 794 | 795 | ```Ruby 796 | # bad - braces are required because of op precedence 797 | x = (not something) 798 | 799 | # good 800 | x = !something 801 | ``` 802 | 803 | * 804 | Avoid the use of `!!`. 805 | [[link](#no-bang-bang)] 806 | 807 | ```Ruby 808 | # bad 809 | x = 'test' 810 | # obscure nil check 811 | if !!x 812 | # body omitted 813 | end 814 | 815 | x = false 816 | # double negation is useless on booleans 817 | !!x # => false 818 | 819 | # good 820 | x = 'test' 821 | unless x.nil? 822 | # body omitted 823 | end 824 | ``` 825 | 826 | * 827 | The `and` and `or` keywords are banned. It's just not worth it. Always use 828 | `&&` and `||` instead. 829 | [[link](#no-and-or-or)] 830 | 831 | ```Ruby 832 | # bad 833 | # boolean expression 834 | if some_condition and some_other_condition 835 | do_something 836 | end 837 | 838 | # control flow 839 | document.saved? or document.save! 840 | 841 | # good 842 | # boolean expression 843 | if some_condition && some_other_condition 844 | do_something 845 | end 846 | 847 | # control flow 848 | document.saved? || document.save! 849 | ``` 850 | 851 | * 852 | Avoid multi-line `?:` (the ternary operator); use `if/unless` instead. 853 | [[link](#no-multiline-ternary)] 854 | 855 | * 856 | Favor modifier `if/unless` usage when you have a single-line body. Another 857 | good alternative is the usage of control flow `&&/||`. 858 | [[link](#if-as-a-modifier)] 859 | 860 | ```Ruby 861 | # bad 862 | if some_condition 863 | do_something 864 | end 865 | 866 | # good 867 | do_something if some_condition 868 | 869 | # another good option 870 | some_condition && do_something 871 | ``` 872 | 873 | * 874 | Avoid modifier `if/unless` usage at the end of a non-trivial multi-line 875 | block. 876 | [[link](#no-multiline-if-modifiers)] 877 | 878 | ```Ruby 879 | # bad 880 | 10.times do 881 | # multi-line body omitted 882 | end if some_condition 883 | 884 | # good 885 | if some_condition 886 | 10.times do 887 | # multi-line body omitted 888 | end 889 | end 890 | ``` 891 | 892 | * 893 | Favor `unless` over `if` for negative conditions (or control flow `||`). 894 | [[link](#unless-for-negatives)] 895 | 896 | ```Ruby 897 | # bad 898 | do_something if !some_condition 899 | 900 | # bad 901 | do_something if not some_condition 902 | 903 | # good 904 | do_something unless some_condition 905 | 906 | # another good option 907 | some_condition || do_something 908 | ``` 909 | 910 | * 911 | Do not use `unless` with `else`. Rewrite these with the positive case first. 912 | [[link](#no-else-with-unless)] 913 | 914 | ```Ruby 915 | # bad 916 | unless success? 917 | puts 'failure' 918 | else 919 | puts 'success' 920 | end 921 | 922 | # good 923 | if success? 924 | puts 'success' 925 | else 926 | puts 'failure' 927 | end 928 | ``` 929 | 930 | * 931 | Don't use parentheses around the condition of an `if/unless/while/until`. 932 | [[link](#no-parens-if)] 933 | 934 | ```Ruby 935 | # bad 936 | if (x > 10) 937 | # body omitted 938 | end 939 | 940 | # good 941 | if x > 10 942 | # body omitted 943 | end 944 | ``` 945 | 946 | Note that there is an exception to this rule, namely [safe assignment in 947 | condition](#safe-assignment-in-condition). 948 | 949 | * 950 | Do not use `while/until condition do` for multi-line `while/until`. 951 | [[link](#no-multiline-while-do)] 952 | 953 | ```Ruby 954 | # bad 955 | while x > 5 do 956 | # body omitted 957 | end 958 | 959 | until x > 5 do 960 | # body omitted 961 | end 962 | 963 | # good 964 | while x > 5 965 | # body omitted 966 | end 967 | 968 | until x > 5 969 | # body omitted 970 | end 971 | ``` 972 | 973 | * 974 | Favor modifier `while/until` usage when you have a single-line body. 975 | [[link](#while-as-a-modifier)] 976 | 977 | ```Ruby 978 | # bad 979 | while some_condition 980 | do_something 981 | end 982 | 983 | # good 984 | do_something while some_condition 985 | ``` 986 | 987 | * 988 | Favor `until` over `while` for negative conditions. 989 | [[link](#until-for-negatives)] 990 | 991 | ```Ruby 992 | # bad 993 | do_something while !some_condition 994 | 995 | # good 996 | do_something until some_condition 997 | ``` 998 | 999 | * 1000 | Use `Kernel#loop` instead of `while/until` when you need an infinite loop. 1001 | [[link](#infinite-loop)] 1002 | 1003 | ```ruby 1004 | # bad 1005 | while true 1006 | do_something 1007 | end 1008 | 1009 | until false 1010 | do_something 1011 | end 1012 | 1013 | # good 1014 | loop do 1015 | do_something 1016 | end 1017 | ``` 1018 | 1019 | * 1020 | Use `Kernel#loop` with `break` rather than `begin/end/until` or 1021 | `begin/end/while` for post-loop tests. 1022 | [[link](#loop-with-break)] 1023 | 1024 | ```Ruby 1025 | # bad 1026 | begin 1027 | puts val 1028 | val += 1 1029 | end while val < 0 1030 | 1031 | # good 1032 | loop do 1033 | puts val 1034 | val += 1 1035 | break unless val < 0 1036 | end 1037 | ``` 1038 | 1039 | * 1040 | Omit parentheses around parameters for methods that are part of an internal 1041 | DSL (e.g. Rake, Rails, RSpec), methods that have "keyword" status in Ruby 1042 | (e.g. `attr_reader`, `puts`) and attribute access methods. Use parentheses 1043 | around the arguments of all other method invocations. 1044 | [[link](#no-dsl-parens)] 1045 | 1046 | ```Ruby 1047 | class Person 1048 | attr_reader :name, :age 1049 | 1050 | # omitted 1051 | end 1052 | 1053 | temperance = Person.new('Temperance', 30) 1054 | temperance.name 1055 | 1056 | puts temperance.age 1057 | 1058 | x = Math.sin(y) 1059 | array.delete(e) 1060 | 1061 | bowling.score.should == 0 1062 | ``` 1063 | 1064 | * 1065 | Omit the outer braces around an implicit options hash. 1066 | [[link](#no-braces-opts-hash)] 1067 | 1068 | ```Ruby 1069 | # bad 1070 | user.set({ name: 'John', age: 45, permissions: { read: true } }) 1071 | 1072 | # good 1073 | user.set(name: 'John', age: 45, permissions: { read: true }) 1074 | ``` 1075 | 1076 | * 1077 | Omit both the outer braces and parentheses for methods that are part of an 1078 | internal DSL. 1079 | [[link](#no-dsl-decorating)] 1080 | 1081 | ```Ruby 1082 | class Person < ActiveRecord::Base 1083 | # bad 1084 | validates(:name, { presence: true, length: { within: 1..10 } }) 1085 | 1086 | # good 1087 | validates :name, presence: true, length: { within: 1..10 } 1088 | end 1089 | ``` 1090 | 1091 | * 1092 | Omit parentheses for method calls with no arguments. 1093 | [[link](#no-args-no-parens)] 1094 | 1095 | ```Ruby 1096 | # bad 1097 | Kernel.exit!() 1098 | 2.even?() 1099 | fork() 1100 | 'test'.upcase() 1101 | 1102 | # good 1103 | Kernel.exit! 1104 | 2.even? 1105 | fork 1106 | 'test'.upcase 1107 | ``` 1108 | 1109 | * 1110 | Prefer `{...}` over `do...end` for single-line blocks. Avoid using `{...}` 1111 | for multi-line blocks (multiline chaining is always ugly). Always use 1112 | `do...end` for "control flow" and "method definitions" (e.g. in Rakefiles and 1113 | certain DSLs). Avoid `do...end` when chaining. 1114 | [[link](#single-line-blocks)] 1115 | 1116 | ```Ruby 1117 | names = ['Bozhidar', 'Steve', 'Sarah'] 1118 | 1119 | # bad 1120 | names.each do |name| 1121 | puts name 1122 | end 1123 | 1124 | # good 1125 | names.each { |name| puts name } 1126 | 1127 | # bad 1128 | names.select do |name| 1129 | name.start_with?('S') 1130 | end.map { |name| name.upcase } 1131 | 1132 | # good 1133 | names.select { |name| name.start_with?('S') }.map { |name| name.upcase } 1134 | ``` 1135 | 1136 | Some will argue that multiline chaining would look OK with the use of {...}, 1137 | but they should ask themselves - is this code really readable and can the 1138 | blocks' contents be extracted into nifty methods? 1139 | 1140 | * 1141 | Consider using explicit block argument to avoid writing block literal that 1142 | just passes its arguments to another block. Beware of the performance impact, 1143 | though, as the block gets converted to a Proc. 1144 | [[link](#block-argument)] 1145 | 1146 | ```Ruby 1147 | require 'tempfile' 1148 | 1149 | # bad 1150 | def with_tmp_dir 1151 | Dir.mktmpdir do |tmp_dir| 1152 | Dir.chdir(tmp_dir) { |dir| yield dir } # block just passes arguments 1153 | end 1154 | end 1155 | 1156 | # good 1157 | def with_tmp_dir(&block) 1158 | Dir.mktmpdir do |tmp_dir| 1159 | Dir.chdir(tmp_dir, &block) 1160 | end 1161 | end 1162 | 1163 | with_tmp_dir do |dir| 1164 | puts "dir is accessible as a parameter and pwd is set: #{dir}" 1165 | end 1166 | ``` 1167 | 1168 | * 1169 | Avoid `return` where not required for flow of control. 1170 | [[link](#no-explicit-return)] 1171 | 1172 | ```Ruby 1173 | # bad 1174 | def some_method(some_arr) 1175 | return some_arr.size 1176 | end 1177 | 1178 | # good 1179 | def some_method(some_arr) 1180 | some_arr.size 1181 | end 1182 | ``` 1183 | 1184 | * 1185 | Avoid `self` where not required. (It is only required when calling a self 1186 | write accessor.) 1187 | [[link](#no-self-unless-required)] 1188 | 1189 | ```Ruby 1190 | # bad 1191 | def ready? 1192 | if self.last_reviewed_at > self.last_updated_at 1193 | self.worker.update(self.content, self.options) 1194 | self.status = :in_progress 1195 | end 1196 | self.status == :verified 1197 | end 1198 | 1199 | # good 1200 | def ready? 1201 | if last_reviewed_at > last_updated_at 1202 | worker.update(content, options) 1203 | self.status = :in_progress 1204 | end 1205 | status == :verified 1206 | end 1207 | ``` 1208 | 1209 | * 1210 | As a corollary, avoid shadowing methods with local variables unless they are 1211 | both equivalent. 1212 | [[link](#no-shadowing)] 1213 | 1214 | ```Ruby 1215 | class Foo 1216 | attr_accessor :options 1217 | 1218 | # ok 1219 | def initialize(options) 1220 | self.options = options 1221 | # both options and self.options are equivalent here 1222 | end 1223 | 1224 | # bad 1225 | def do_something(options = {}) 1226 | unless options[:when] == :later 1227 | output(self.options[:message]) 1228 | end 1229 | end 1230 | 1231 | # good 1232 | def do_something(params = {}) 1233 | unless params[:when] == :later 1234 | output(options[:message]) 1235 | end 1236 | end 1237 | end 1238 | ``` 1239 | 1240 | * 1241 | Don't use the return value of `=` (an assignment) in conditional expressions 1242 | unless the assignment is wrapped in parentheses. This is a fairly popular 1243 | idiom among Rubyists that's sometimes referred to as *safe assignment in 1244 | condition*. 1245 | [[link](#safe-assignment-in-condition)] 1246 | 1247 | ```Ruby 1248 | # bad (+ a warning) 1249 | if v = array.grep(/foo/) 1250 | do_something(v) 1251 | ... 1252 | end 1253 | 1254 | # good (MRI would still complain, but RuboCop won't) 1255 | if (v = array.grep(/foo/)) 1256 | do_something(v) 1257 | ... 1258 | end 1259 | 1260 | # good 1261 | v = array.grep(/foo/) 1262 | if v 1263 | do_something(v) 1264 | ... 1265 | end 1266 | ``` 1267 | 1268 | * 1269 | Use shorthand self assignment operators whenever applicable. 1270 | [[link](#self-assignment)] 1271 | 1272 | ```Ruby 1273 | # bad 1274 | x = x + y 1275 | x = x * y 1276 | x = x**y 1277 | x = x / y 1278 | x = x || y 1279 | x = x && y 1280 | 1281 | # good 1282 | x += y 1283 | x *= y 1284 | x **= y 1285 | x /= y 1286 | x ||= y 1287 | x &&= y 1288 | ``` 1289 | 1290 | * 1291 | Use `||=` to initialize variables only if they're not already initialized. 1292 | [[link](#double-pipe-for-uninit)] 1293 | 1294 | ```Ruby 1295 | # bad 1296 | name = name ? name : 'Bozhidar' 1297 | 1298 | # bad 1299 | name = 'Bozhidar' unless name 1300 | 1301 | # good - set name to Bozhidar, only if it's nil or false 1302 | name ||= 'Bozhidar' 1303 | ``` 1304 | 1305 | * 1306 | Don't use `||=` to initialize boolean variables. (Consider what would happen 1307 | if the current value happened to be `false`.) 1308 | [[link](#no-double-pipes-for-bools)] 1309 | 1310 | ```Ruby 1311 | # bad - would set enabled to true even if it was false 1312 | enabled ||= true 1313 | 1314 | # good 1315 | enabled = true if enabled.nil? 1316 | ``` 1317 | 1318 | * 1319 | Use `&&=` to preprocess variables that may or may not exist. Using `&&=` 1320 | will change the value only if it exists, removing the need to check its 1321 | existence with `if`. 1322 | [[link](#double-amper-preprocess)] 1323 | 1324 | ```Ruby 1325 | # bad 1326 | if something 1327 | something = something.downcase 1328 | end 1329 | 1330 | # bad 1331 | something = something ? something.downcase : nil 1332 | 1333 | # ok 1334 | something = something.downcase if something 1335 | 1336 | # good 1337 | something = something && something.downcase 1338 | 1339 | # better 1340 | something &&= something.downcase 1341 | ``` 1342 | 1343 | * 1344 | Avoid explicit use of the case equality operator `===`. As its name implies 1345 | it is meant to be used implicitly by `case` expressions and outside of them it 1346 | yields some pretty confusing code. 1347 | [[link](#no-case-equality)] 1348 | 1349 | ```Ruby 1350 | # bad 1351 | Array === something 1352 | (1..100) === 7 1353 | /something/ === some_string 1354 | 1355 | # good 1356 | something.is_a?(Array) 1357 | (1..100).include?(7) 1358 | some_string =~ /something/ 1359 | ``` 1360 | 1361 | * 1362 | Do not use `eql?` when using `==` will do. The stricter comparison semantics 1363 | provided by `eql?` are rarely needed in practice. 1364 | [[link](#eql)] 1365 | 1366 | ```Ruby 1367 | # bad - eql? is the same as == for strings 1368 | "ruby".eql? some_str 1369 | 1370 | # good 1371 | "ruby" == some_str 1372 | 1.0.eql? x # eql? makes sense here if want to differentiate between Fixnum and Float 1 1373 | ``` 1374 | 1375 | * 1376 | Avoid using Perl-style special variables (like `$:`, `$;`, etc. ). They are 1377 | quite cryptic and their use in anything but one-liner scripts is discouraged. 1378 | Use the human-friendly aliases provided by the `English` library. 1379 | [[link](#no-cryptic-perlisms)] 1380 | 1381 | ```Ruby 1382 | # bad 1383 | $:.unshift File.dirname(__FILE__) 1384 | 1385 | # good 1386 | require 'English' 1387 | $LOAD_PATH.unshift File.dirname(__FILE__) 1388 | ``` 1389 | 1390 | * 1391 | Do not put a space between a method name and the opening parenthesis. 1392 | [[link](#parens-no-spaces)] 1393 | 1394 | ```Ruby 1395 | # bad 1396 | f (3 + 2) + 1 1397 | 1398 | # good 1399 | f(3 + 2) + 1 1400 | ``` 1401 | 1402 | * 1403 | If the first argument to a method begins with an open parenthesis, always 1404 | use parentheses in the method invocation. For example, write `f((3 + 2) + 1)`. 1405 | [[link](#parens-as-args)] 1406 | 1407 | * 1408 | Always run the Ruby interpreter with the `-w` option so it will warn you if 1409 | you forget either of the rules above! 1410 | [[link](#always-warn-at-runtime)] 1411 | 1412 | * 1413 | Use the new lambda literal syntax for single line body blocks. Use the 1414 | `lambda` method for multi-line blocks. 1415 | [[link](#lambda-multi-line)] 1416 | 1417 | ```Ruby 1418 | # bad 1419 | l = lambda { |a, b| a + b } 1420 | l.call(1, 2) 1421 | 1422 | # correct, but looks extremely awkward 1423 | l = ->(a, b) do 1424 | tmp = a * 7 1425 | tmp * b / 50 1426 | end 1427 | 1428 | # good 1429 | l = ->(a, b) { a + b } 1430 | l.call(1, 2) 1431 | 1432 | l = lambda do |a, b| 1433 | tmp = a * 7 1434 | tmp * b / 50 1435 | end 1436 | ``` 1437 | 1438 | * 1439 | Prefer `proc` over `Proc.new`. 1440 | [[link](#proc)] 1441 | 1442 | ```Ruby 1443 | # bad 1444 | p = Proc.new { |n| puts n } 1445 | 1446 | # good 1447 | p = proc { |n| puts n } 1448 | ``` 1449 | 1450 | * 1451 | Prefer `proc.call()` over `proc[]` or `proc.()` for both lambdas and procs. 1452 | [[link](#proc-call)] 1453 | 1454 | ```Ruby 1455 | # bad - looks similar to Enumeration access 1456 | l = ->(v) { puts v } 1457 | l[1] 1458 | 1459 | # also bad - uncommon syntax 1460 | l = ->(v) { puts v } 1461 | l.(1) 1462 | 1463 | # good 1464 | l = ->(v) { puts v } 1465 | l.call(1) 1466 | ``` 1467 | 1468 | * 1469 | Prefix with `_` unused block parameters and local variables. It's also 1470 | acceptable to use just `_` (although it's a bit less descriptive). This 1471 | convention is recognized by the Ruby interpreter and tools like RuboCop and 1472 | will suppress their unused variable warnings. 1473 | [[link](#underscore-unused-vars)] 1474 | 1475 | ```Ruby 1476 | # bad 1477 | result = hash.map { |k, v| v + 1 } 1478 | 1479 | def something(x) 1480 | unused_var, used_var = something_else(x) 1481 | # ... 1482 | end 1483 | 1484 | # good 1485 | result = hash.map { |_k, v| v + 1 } 1486 | 1487 | def something(x) 1488 | _unused_var, used_var = something_else(x) 1489 | # ... 1490 | end 1491 | 1492 | # good 1493 | result = hash.map { |_, v| v + 1 } 1494 | 1495 | def something(x) 1496 | _, used_var = something_else(x) 1497 | # ... 1498 | end 1499 | ``` 1500 | 1501 | * 1502 | Use `$stdout/$stderr/$stdin` instead of `STDOUT/STDERR/STDIN`. 1503 | `STDOUT/STDERR/STDIN` are constants, and while you can actually reassign 1504 | (possibly to redirect some stream) constants in Ruby, you'll get an 1505 | interpreter warning if you do so. 1506 | [[link](#global-stdout)] 1507 | 1508 | * 1509 | Use `warn` instead of `$stderr.puts`. Apart from being more concise and 1510 | clear, `warn` allows you to suppress warnings if you need to (by setting the 1511 | warn level to 0 via `-W0`). 1512 | [[link](#warn)] 1513 | 1514 | * 1515 | Favor the use of `sprintf` and its alias `format` over the fairly cryptic 1516 | `String#%` method. 1517 | [[link](#sprintf)] 1518 | 1519 | ```Ruby 1520 | # bad 1521 | '%d %d' % [20, 10] 1522 | # => '20 10' 1523 | 1524 | # good 1525 | sprintf('%d %d', 20, 10) 1526 | # => '20 10' 1527 | 1528 | # good 1529 | sprintf('%{first} %{second}', first: 20, second: 10) 1530 | # => '20 10' 1531 | 1532 | format('%d %d', 20, 10) 1533 | # => '20 10' 1534 | 1535 | # good 1536 | format('%{first} %{second}', first: 20, second: 10) 1537 | # => '20 10' 1538 | ``` 1539 | 1540 | * 1541 | Favor the use of `Array#join` over the fairly cryptic `Array#*` with 1542 | [[link](#array-join)] 1543 | a string argument. 1544 | 1545 | ```Ruby 1546 | # bad 1547 | %w(one two three) * ', ' 1548 | # => 'one, two, three' 1549 | 1550 | # good 1551 | %w(one two three).join(', ') 1552 | # => 'one, two, three' 1553 | ``` 1554 | 1555 | * 1556 | Use `[*var]` or `Array()` instead of explicit `Array` check, when dealing 1557 | with a variable you want to treat as an Array, but you're not certain it's an 1558 | array. 1559 | [[link](#splat-arrays)] 1560 | 1561 | ```Ruby 1562 | # bad 1563 | paths = [paths] unless paths.is_a? Array 1564 | paths.each { |path| do_something(path) } 1565 | 1566 | # good 1567 | [*paths].each { |path| do_something(path) } 1568 | 1569 | # good (and a bit more readable) 1570 | Array(paths).each { |path| do_something(path) } 1571 | ``` 1572 | 1573 | * 1574 | Use ranges or `Comparable#between?` instead of complex comparison logic when 1575 | possible. 1576 | [[link](#ranges-or-between)] 1577 | 1578 | ```Ruby 1579 | # bad 1580 | do_something if x >= 1000 && x <= 2000 1581 | 1582 | # good 1583 | do_something if (1000..2000).include?(x) 1584 | 1585 | # good 1586 | do_something if x.between?(1000, 2000) 1587 | ``` 1588 | 1589 | * 1590 | Favor the use of predicate methods to explicit comparisons with `==`. 1591 | Numeric comparisons are OK. 1592 | [[link](#predicate-methods)] 1593 | 1594 | ```Ruby 1595 | # bad 1596 | if x % 2 == 0 1597 | end 1598 | 1599 | if x % 2 == 1 1600 | end 1601 | 1602 | if x == nil 1603 | end 1604 | 1605 | # good 1606 | if x.even? 1607 | end 1608 | 1609 | if x.odd? 1610 | end 1611 | 1612 | if x.nil? 1613 | end 1614 | 1615 | if x.zero? 1616 | end 1617 | 1618 | if x == 0 1619 | end 1620 | ``` 1621 | 1622 | * 1623 | Don't do explicit non-`nil` checks unless you're dealing with boolean 1624 | values. 1625 | [[link](#no-non-nil-checks)] 1626 | 1627 | ```ruby 1628 | # bad 1629 | do_something if !something.nil? 1630 | do_something if something != nil 1631 | 1632 | # good 1633 | do_something if something 1634 | 1635 | # good - dealing with a boolean 1636 | def value_set? 1637 | !@some_boolean.nil? 1638 | end 1639 | ``` 1640 | 1641 | * 1642 | Avoid the use of `BEGIN` blocks. 1643 | [[link](#no-BEGIN-blocks)] 1644 | 1645 | * 1646 | Do not use `END` blocks. Use `Kernel#at_exit` instead. 1647 | [[link](#no-END-blocks)] 1648 | 1649 | ```ruby 1650 | # bad 1651 | END { puts 'Goodbye!' } 1652 | 1653 | # good 1654 | at_exit { puts 'Goodbye!' } 1655 | ``` 1656 | 1657 | * 1658 | Avoid the use of flip-flops. 1659 | [[link](#no-flip-flops)] 1660 | 1661 | * 1662 | Avoid use of nested conditionals for flow of control. 1663 | [[link](#no-nested-conditionals)] 1664 | 1665 | Prefer a guard clause when you can assert invalid data. A guard clause 1666 | is a conditional statement at the top of a function that bails out as 1667 | soon as it can. 1668 | 1669 | ```Ruby 1670 | # bad 1671 | def compute_thing(thing) 1672 | if thing[:foo] 1673 | update_with_bar(thing) 1674 | if thing[:foo][:bar] 1675 | partial_compute(thing) 1676 | else 1677 | re_compute(thing) 1678 | end 1679 | end 1680 | end 1681 | 1682 | # good 1683 | def compute_thing(thing) 1684 | return unless thing[:foo] 1685 | update_with_bar(thing[:foo]) 1686 | return re_compute(thing) unless thing[:foo][:bar] 1687 | partial_compute(thing) 1688 | end 1689 | ``` 1690 | 1691 | Prefer `next` in loops instead of conditional blocks. 1692 | 1693 | ```Ruby 1694 | # bad 1695 | [0, 1, 2, 3].each do |item| 1696 | if item > 1 1697 | puts item 1698 | end 1699 | end 1700 | 1701 | # good 1702 | [0, 1, 2, 3].each do |item| 1703 | next unless item > 1 1704 | puts item 1705 | end 1706 | ``` 1707 | 1708 | * 1709 | Prefer `map` over `collect`, `find` over `detect`, `select` over `find_all`, 1710 | `reduce` over `inject` and `size` over `length`. This is not a hard 1711 | requirement; if the use of the alias enhances readability, it's ok to use it. 1712 | The rhyming methods are inherited from Smalltalk and are not common in other 1713 | programming languages. The reason the use of `select` is encouraged over 1714 | `find_all` is that it goes together nicely with `reject` and its name is 1715 | pretty self-explanatory. 1716 | [[link](#map-find-select-reduce-size)] 1717 | 1718 | * 1719 | Don't use `count` as a substitute for `size`. For `Enumerable` objects other 1720 | than `Array` it will iterate the entire collection in order to determine its 1721 | size. 1722 | [[link](#count-vs-size)] 1723 | 1724 | ```Ruby 1725 | # bad 1726 | some_hash.count 1727 | 1728 | # good 1729 | some_hash.size 1730 | ``` 1731 | 1732 | * 1733 | Use `flat_map` instead of `map` + `flatten`. This does not apply for arrays 1734 | with a depth greater than 2, i.e. if `users.first.songs == ['a', ['b','c']]`, 1735 | then use `map + flatten` rather than `flat_map`. `flat_map` flattens the 1736 | array by 1, whereas `flatten` flattens it all the way. 1737 | [[link](#flat-map)] 1738 | 1739 | ```Ruby 1740 | # bad 1741 | all_songs = users.map(&:songs).flatten.uniq 1742 | 1743 | # good 1744 | all_songs = users.flat_map(&:songs).uniq 1745 | ``` 1746 | 1747 | * 1748 | Use `reverse_each` instead of `reverse.each`. `reverse_each` doesn't do a 1749 | new array allocation and that's a good thing. 1750 | [[link](#reverse-each)] 1751 | 1752 | ```Ruby 1753 | # bad 1754 | array.reverse.each { ... } 1755 | 1756 | # good 1757 | array.reverse_each { ... } 1758 | ``` 1759 | 1760 | ## Naming 1761 | 1762 | > The only real difficulties in programming are cache invalidation and 1763 | > naming things.
1764 | > -- Phil Karlton 1765 | 1766 | * 1767 | Name identifiers in English. 1768 | [[link](#english-identifiers)] 1769 | 1770 | ```Ruby 1771 | # bad - identifier using non-ascii characters 1772 | заплата = 1_000 1773 | 1774 | # bad - identifier is a Bulgarian word, written with Latin letters (instead of Cyrillic) 1775 | zaplata = 1_000 1776 | 1777 | # good 1778 | salary = 1_000 1779 | ``` 1780 | 1781 | * 1782 | Use `snake_case` for symbols, methods and variables. 1783 | [[link](#snake-case-symbols-methods-vars)] 1784 | 1785 | ```Ruby 1786 | # bad 1787 | :'some symbol' 1788 | :SomeSymbol 1789 | :someSymbol 1790 | 1791 | someVar = 5 1792 | 1793 | def someMethod 1794 | ... 1795 | end 1796 | 1797 | def SomeMethod 1798 | ... 1799 | end 1800 | 1801 | # good 1802 | :some_symbol 1803 | 1804 | def some_method 1805 | ... 1806 | end 1807 | ``` 1808 | 1809 | * 1810 | Use `CamelCase` for classes and modules. (Keep acronyms like HTTP, RFC, XML 1811 | uppercase.) 1812 | [[link](#camelcase-classes)] 1813 | 1814 | ```Ruby 1815 | # bad 1816 | class Someclass 1817 | ... 1818 | end 1819 | 1820 | class Some_Class 1821 | ... 1822 | end 1823 | 1824 | class SomeXml 1825 | ... 1826 | end 1827 | 1828 | # good 1829 | class SomeClass 1830 | ... 1831 | end 1832 | 1833 | class SomeXML 1834 | ... 1835 | end 1836 | ``` 1837 | 1838 | * 1839 | Use `snake_case` for naming files, e.g. `hello_world.rb`. 1840 | [[link](#snake-case-files)] 1841 | 1842 | * 1843 | Use `snake_case` for naming directories, e.g. 1844 | `lib/hello_world/hello_world.rb`. 1845 | [[link](#snake-case-dirs)] 1846 | 1847 | * 1848 | Aim to have just a single class/module per source file. Name the file name 1849 | as the class/module, but replacing CamelCase with snake_case. 1850 | [[link](#one-class-per-file)] 1851 | 1852 | * 1853 | Use `SCREAMING_SNAKE_CASE` for other constants. 1854 | [[link](#screaming-snake-case)] 1855 | 1856 | ```Ruby 1857 | # bad 1858 | SomeConst = 5 1859 | 1860 | # good 1861 | SOME_CONST = 5 1862 | ``` 1863 | 1864 | * 1865 | The names of predicate methods (methods that return a boolean value) should 1866 | end in a question mark. (i.e. `Array#empty?`). Methods that don't return a 1867 | boolean, shouldn't end in a question mark. 1868 | [[link](#bool-methods-qmark)] 1869 | 1870 | * 1871 | The names of potentially *dangerous* methods (i.e. methods that modify 1872 | `self` or the arguments, `exit!` (doesn't run the finalizers like `exit` 1873 | does), etc.) should end with an exclamation mark if there exists a safe 1874 | version of that *dangerous* method. 1875 | [[link](#dangerous-method-bang)] 1876 | 1877 | ```Ruby 1878 | # bad - there is no matching 'safe' method 1879 | class Person 1880 | def update! 1881 | end 1882 | end 1883 | 1884 | # good 1885 | class Person 1886 | def update 1887 | end 1888 | end 1889 | 1890 | # good 1891 | class Person 1892 | def update! 1893 | end 1894 | 1895 | def update 1896 | end 1897 | end 1898 | ``` 1899 | 1900 | * 1901 | Define the non-bang (safe) method in terms of the bang (dangerous) one if 1902 | possible. 1903 | [[link](#safe-because-unsafe)] 1904 | 1905 | ```Ruby 1906 | class Array 1907 | def flatten_once! 1908 | res = [] 1909 | 1910 | each do |e| 1911 | [*e].each { |f| res << f } 1912 | end 1913 | 1914 | replace(res) 1915 | end 1916 | 1917 | def flatten_once 1918 | dup.flatten_once! 1919 | end 1920 | end 1921 | ``` 1922 | 1923 | * 1924 | When using `reduce` with short blocks, name the arguments `|a, e|` 1925 | (accumulator, element). 1926 | [[link](#reduce-blocks)] 1927 | 1928 | * 1929 | When defining binary operators, name the parameter `other`(`<<` and `[]` are 1930 | exceptions to the rule, since their semantics are different). 1931 | [[link](#other-arg)] 1932 | 1933 | ```Ruby 1934 | def +(other) 1935 | # body omitted 1936 | end 1937 | ``` 1938 | 1939 | ## Comments 1940 | 1941 | > Good code is its own best documentation. As you're about to add a 1942 | > comment, ask yourself, "How can I improve the code so that this 1943 | > comment isn't needed?" Improve the code and then document it to make 1944 | > it even clearer.
1945 | > -- Steve McConnell 1946 | 1947 | * 1948 | Write self-documenting code and ignore the rest of this section. Seriously! 1949 | [[link](#no-comments)] 1950 | 1951 | * 1952 | Write comments in English. 1953 | [[link](#english-comments)] 1954 | 1955 | * 1956 | Use one space between the leading `#` character of the comment and the text 1957 | of the comment. 1958 | [[link](#hash-space)] 1959 | 1960 | * 1961 | Comments longer than a word are capitalized and use punctuation. Use [one 1962 | space](http://en.wikipedia.org/wiki/Sentence_spacing) after periods. 1963 | [[link](#english-syntax)] 1964 | 1965 | * 1966 | Avoid superfluous comments. 1967 | [[link](#no-superfluous-comments)] 1968 | 1969 | ```Ruby 1970 | # bad 1971 | counter += 1 # Increments counter by one. 1972 | ``` 1973 | 1974 | * 1975 | Keep existing comments up-to-date. An outdated comment is worse than no 1976 | comment at all. 1977 | [[link](#comment-upkeep)] 1978 | 1979 | > Good code is like a good joke - it needs no explanation.
1980 | > -- Russ Olsen 1981 | 1982 | * 1983 | Avoid writing comments to explain bad code. Refactor the code to make it 1984 | self-explanatory. (Do or do not - there is no try. --Yoda) 1985 | [[link](#refactor-dont-comment)] 1986 | 1987 | ### Comment Annotations 1988 | 1989 | * 1990 | Annotations should usually be written on the line immediately above the 1991 | relevant code. 1992 | [[link](#annotate-above)] 1993 | 1994 | * 1995 | The annotation keyword is followed by a colon and a space, then a note 1996 | describing the problem. 1997 | [[link](#annotate-keywords)] 1998 | 1999 | * 2000 | If multiple lines are required to describe the problem, subsequent lines 2001 | should be indented three spaces after the `#` (one general plus two for 2002 | indentation purpose). 2003 | [[link](#indent-annotations)] 2004 | 2005 | ```Ruby 2006 | def bar 2007 | # FIXME: This has crashed occasionally since v3.2.1. It may 2008 | # be related to the BarBazUtil upgrade. 2009 | baz(:quux) 2010 | end 2011 | ``` 2012 | 2013 | * 2014 | In cases where the problem is so obvious that any documentation would be 2015 | redundant, annotations may be left at the end of the offending line with no 2016 | note. This usage should be the exception and not the rule. 2017 | [[link](#rare-eol-annotations)] 2018 | 2019 | ```Ruby 2020 | def bar 2021 | sleep 100 # OPTIMIZE 2022 | end 2023 | ``` 2024 | 2025 | * 2026 | Use `TODO` to note missing features or functionality that should be added at 2027 | a later date. 2028 | [[link](#todo)] 2029 | 2030 | * 2031 | Use `FIXME` to note broken code that needs to be fixed. 2032 | [[link](#fixme)] 2033 | 2034 | * 2035 | Use `OPTIMIZE` to note slow or inefficient code that may cause performance 2036 | problems. 2037 | [[link](#optimize)] 2038 | 2039 | * 2040 | Use `HACK` to note code smells where questionable coding practices were used 2041 | and should be refactored away. 2042 | [[link](#hack)] 2043 | 2044 | * 2045 | Use `REVIEW` to note anything that should be looked at to confirm it is 2046 | working as intended. For example: `REVIEW: Are we sure this is how the client 2047 | does X currently?` 2048 | [[link](#review)] 2049 | 2050 | * 2051 | Use other custom annotation keywords if it feels appropriate, but be sure to 2052 | document them in your project's `README` or similar. 2053 | [[link](#document-annotations)] 2054 | 2055 | ## Classes & Modules 2056 | 2057 | * 2058 | Use a consistent structure in your class definitions. 2059 | [[link](#consistent-classes)] 2060 | 2061 | ```Ruby 2062 | class Person 2063 | # extend and include go first 2064 | extend SomeModule 2065 | include AnotherModule 2066 | 2067 | # inner classes 2068 | CustomErrorKlass = Class.new(StandardError) 2069 | 2070 | # constants are next 2071 | SOME_CONSTANT = 20 2072 | 2073 | # afterwards we have attribute macros 2074 | attr_reader :name 2075 | 2076 | # followed by other macros (if any) 2077 | validates :name 2078 | 2079 | # public class methods are next in line 2080 | def self.some_method 2081 | end 2082 | 2083 | # followed by public instance methods 2084 | def some_method 2085 | end 2086 | 2087 | # protected and private methods are grouped near the end 2088 | protected 2089 | 2090 | def some_protected_method 2091 | end 2092 | 2093 | private 2094 | 2095 | def some_private_method 2096 | end 2097 | end 2098 | ``` 2099 | 2100 | * 2101 | Don't nest multi line classes within classes. Try to have such nested 2102 | classes each in their own file in a folder named like the containing class. 2103 | [[link](#file-classes)] 2104 | 2105 | ```Ruby 2106 | # bad 2107 | 2108 | # foo.rb 2109 | class Foo 2110 | class Bar 2111 | # 30 methods inside 2112 | end 2113 | 2114 | class Car 2115 | # 20 methods inside 2116 | end 2117 | 2118 | # 30 methods inside 2119 | end 2120 | 2121 | # good 2122 | 2123 | # foo.rb 2124 | class Foo 2125 | # 30 methods inside 2126 | end 2127 | 2128 | # foo/bar.rb 2129 | class Foo 2130 | class Bar 2131 | # 30 methods inside 2132 | end 2133 | end 2134 | 2135 | # foo/car.rb 2136 | class Foo 2137 | class Car 2138 | # 20 methods inside 2139 | end 2140 | end 2141 | ``` 2142 | 2143 | * 2144 | Prefer modules to classes with only class methods. Classes should be used 2145 | only when it makes sense to create instances out of them. 2146 | [[link](#modules-vs-classes)] 2147 | 2148 | ```Ruby 2149 | # bad 2150 | class SomeClass 2151 | def self.some_method 2152 | # body omitted 2153 | end 2154 | 2155 | def self.some_other_method 2156 | end 2157 | end 2158 | 2159 | # good 2160 | module SomeModule 2161 | module_function 2162 | 2163 | def some_method 2164 | # body omitted 2165 | end 2166 | 2167 | def some_other_method 2168 | end 2169 | end 2170 | ``` 2171 | 2172 | * 2173 | Favor the use of `module_function` over `extend self` when you want to turn 2174 | a module's instance methods into class methods. 2175 | [[link](#module-function)] 2176 | 2177 | ```Ruby 2178 | # bad 2179 | module Utilities 2180 | extend self 2181 | 2182 | def parse_something(string) 2183 | # do stuff here 2184 | end 2185 | 2186 | def other_utility_method(number, string) 2187 | # do some more stuff 2188 | end 2189 | end 2190 | 2191 | # good 2192 | module Utilities 2193 | module_function 2194 | 2195 | def parse_something(string) 2196 | # do stuff here 2197 | end 2198 | 2199 | def other_utility_method(number, string) 2200 | # do some more stuff 2201 | end 2202 | end 2203 | ``` 2204 | 2205 | * 2206 | When designing class hierarchies make sure that they conform to the [Liskov 2207 | Substitution 2208 | Principle](http://en.wikipedia.org/wiki/Liskov_substitution_principle). 2209 | [[link](#liskov)] 2210 | 2211 | * 2212 | Try to make your classes as 2213 | [SOLID](http://en.wikipedia.org/wiki/SOLID_\(object-oriented_design\)) as 2214 | possible. 2215 | [[link](#solid-design)] 2216 | 2217 | * 2218 | Always supply a proper `to_s` method for classes that represent domain 2219 | objects. 2220 | [[link](#define-to-s)] 2221 | 2222 | ```Ruby 2223 | class Person 2224 | attr_reader :first_name, :last_name 2225 | 2226 | def initialize(first_name, last_name) 2227 | @first_name = first_name 2228 | @last_name = last_name 2229 | end 2230 | 2231 | def to_s 2232 | "#{@first_name} #{@last_name}" 2233 | end 2234 | end 2235 | ``` 2236 | 2237 | * 2238 | Use the `attr` family of functions to define trivial accessors or mutators. 2239 | [[link](#attr_family)] 2240 | 2241 | ```Ruby 2242 | # bad 2243 | class Person 2244 | def initialize(first_name, last_name) 2245 | @first_name = first_name 2246 | @last_name = last_name 2247 | end 2248 | 2249 | def first_name 2250 | @first_name 2251 | end 2252 | 2253 | def last_name 2254 | @last_name 2255 | end 2256 | end 2257 | 2258 | # good 2259 | class Person 2260 | attr_reader :first_name, :last_name 2261 | 2262 | def initialize(first_name, last_name) 2263 | @first_name = first_name 2264 | @last_name = last_name 2265 | end 2266 | end 2267 | ``` 2268 | 2269 | * 2270 | Avoid the use of `attr`. Use `attr_reader` and `attr_accessor` instead. 2271 | [[link](#attr)] 2272 | 2273 | ```Ruby 2274 | # bad - creates a single attribute accessor (deprecated in 1.9) 2275 | attr :something, true 2276 | attr :one, :two, :three # behaves as attr_reader 2277 | 2278 | # good 2279 | attr_accessor :something 2280 | attr_reader :one, :two, :three 2281 | ``` 2282 | 2283 | * 2284 | Consider using `Struct.new`, which defines the trivial accessors, 2285 | constructor and comparison operators for you. 2286 | [[link](#struct-new)] 2287 | 2288 | ```Ruby 2289 | # good 2290 | class Person 2291 | attr_accessor :first_name, :last_name 2292 | 2293 | def initialize(first_name, last_name) 2294 | @first_name = first_name 2295 | @last_name = last_name 2296 | end 2297 | end 2298 | 2299 | # better 2300 | Person = Struct.new(:first_name, :last_name) do 2301 | end 2302 | ```` 2303 | 2304 | * 2305 | Don't extend an instance initialized by `Struct.new`. Extending it introduces 2306 | a superfluous class level and may also introduce weird errors if the file is 2307 | required multiple times. 2308 | [[link](#no-extend-struct-new)] 2309 | 2310 | ```Ruby 2311 | # bad 2312 | class Person < Struct.new(:first_name, :last_name) 2313 | end 2314 | 2315 | # good 2316 | Person = Struct.new(:first_name, :last_name) 2317 | ```` 2318 | 2319 | * 2320 | Consider adding factory methods to provide additional sensible ways to 2321 | create instances of a particular class. 2322 | [[link](#factory-methods)] 2323 | 2324 | ```Ruby 2325 | class Person 2326 | def self.create(options_hash) 2327 | # body omitted 2328 | end 2329 | end 2330 | ``` 2331 | 2332 | * 2333 | Prefer [duck-typing](http://en.wikipedia.org/wiki/Duck_typing) over 2334 | inheritance. 2335 | [[link](#duck-typing)] 2336 | 2337 | ```Ruby 2338 | # bad 2339 | class Animal 2340 | # abstract method 2341 | def speak 2342 | end 2343 | end 2344 | 2345 | # extend superclass 2346 | class Duck < Animal 2347 | def speak 2348 | puts 'Quack! Quack' 2349 | end 2350 | end 2351 | 2352 | # extend superclass 2353 | class Dog < Animal 2354 | def speak 2355 | puts 'Bau! Bau!' 2356 | end 2357 | end 2358 | 2359 | # good 2360 | class Duck 2361 | def speak 2362 | puts 'Quack! Quack' 2363 | end 2364 | end 2365 | 2366 | class Dog 2367 | def speak 2368 | puts 'Bau! Bau!' 2369 | end 2370 | end 2371 | ``` 2372 | 2373 | * 2374 | Avoid the usage of class (`@@`) variables due to their "nasty" behavior in 2375 | inheritance. 2376 | [[link](#no-class-vars)] 2377 | 2378 | ```Ruby 2379 | class Parent 2380 | @@class_var = 'parent' 2381 | 2382 | def self.print_class_var 2383 | puts @@class_var 2384 | end 2385 | end 2386 | 2387 | class Child < Parent 2388 | @@class_var = 'child' 2389 | end 2390 | 2391 | Parent.print_class_var # => will print "child" 2392 | ``` 2393 | 2394 | As you can see all the classes in a class hierarchy actually share one 2395 | class variable. Class instance variables should usually be preferred 2396 | over class variables. 2397 | 2398 | * 2399 | Assign proper visibility levels to methods (`private`, `protected`) in 2400 | accordance with their intended usage. Don't go off leaving everything `public` 2401 | (which is the default). After all we're coding in *Ruby* now, not in *Python*. 2402 | [[link](#visibility)] 2403 | 2404 | * 2405 | Indent the `public`, `protected`, and `private` methods as much as the method 2406 | definitions they apply to. Leave one blank line above the visibility modifier 2407 | and one blank line below in order to emphasize that it applies to all methods 2408 | below it. 2409 | [[link](#indent-public-private-protected)] 2410 | 2411 | ```Ruby 2412 | class SomeClass 2413 | def public_method 2414 | # ... 2415 | end 2416 | 2417 | private 2418 | 2419 | def private_method 2420 | # ... 2421 | end 2422 | 2423 | def another_private_method 2424 | # ... 2425 | end 2426 | end 2427 | ``` 2428 | 2429 | * 2430 | Use `def self.method` to define singleton methods. This makes the code 2431 | easier to refactor since the class name is not repeated. 2432 | [[link](#def-self-singletons)] 2433 | 2434 | ```Ruby 2435 | class TestClass 2436 | # bad 2437 | def TestClass.some_method 2438 | # body omitted 2439 | end 2440 | 2441 | # good 2442 | def self.some_other_method 2443 | # body omitted 2444 | end 2445 | 2446 | # Also possible and convenient when you 2447 | # have to define many singleton methods. 2448 | class << self 2449 | def first_method 2450 | # body omitted 2451 | end 2452 | 2453 | def second_method_etc 2454 | # body omitted 2455 | end 2456 | end 2457 | end 2458 | ``` 2459 | 2460 | * 2461 | Prefer `alias` when aliasing methods in lexical class scope as the 2462 | resolution of `self` in this context is also lexical, and it communicates 2463 | clearly to the user that the indirection of your alias will not be altered 2464 | at runtime or by any subclass unless made explicit. 2465 | [[link](#alias-method-lexically)] 2466 | 2467 | ```Ruby 2468 | class Westerner 2469 | def first_name 2470 | @names.first 2471 | end 2472 | 2473 | alias given_name first_name 2474 | end 2475 | ``` 2476 | 2477 | Since `alias`, like `def`, is a keyword, prefer bareword arguments over 2478 | symbols or strings. In other words, do `alias foo bar`, not 2479 | `alias :foo :bar`. 2480 | 2481 | Also be aware of how Ruby handles aliases and inheritance: an alias 2482 | references the method that was resolved at the time the alias was defined; 2483 | it is not dispatched dynamically. 2484 | 2485 | ```Ruby 2486 | class Fugitive < Westerner 2487 | def first_name 2488 | 'Nobody' 2489 | end 2490 | end 2491 | ``` 2492 | 2493 | In this example, `Fugitive#given_name` would still call the original 2494 | `Westerner#first_name` method, not `Fugitive#first_name`. To override the 2495 | behavior of `Fugitive#given_name` as well, you'd have to redefine it in the 2496 | derived class. 2497 | 2498 | ```Ruby 2499 | class Fugitive < Westerner 2500 | def first_name 2501 | 'Nobody' 2502 | end 2503 | 2504 | alias given_name first_name 2505 | end 2506 | ``` 2507 | 2508 | * 2509 | Always use `alias_method` when aliasing methods of modules, classes, or 2510 | singleton classes at runtime, as the lexical scope of `alias` leads to 2511 | unpredictability in these cases. 2512 | [[link](#alias-method)] 2513 | 2514 | ```Ruby 2515 | module Mononymous 2516 | def self.included(other) 2517 | other.class_eval { alias_method :full_name, :given_name } 2518 | end 2519 | end 2520 | 2521 | class Sting < Westerner 2522 | include Mononymous 2523 | end 2524 | ``` 2525 | 2526 | ## Exceptions 2527 | 2528 | * 2529 | Signal exceptions using the `fail` method. Use `raise` only when catching an 2530 | exception and re-raising it (because here you're not failing, but explicitly 2531 | and purposefully raising an exception). 2532 | [[link](#fail-method)] 2533 | 2534 | ```Ruby 2535 | begin 2536 | fail 'Oops' 2537 | rescue => error 2538 | raise if error.message != 'Oops' 2539 | end 2540 | ``` 2541 | 2542 | * 2543 | Don't specify `RuntimeError` explicitly in the two argument version of 2544 | `fail/raise`. 2545 | [[link](#no-explicit-runtimeerror)] 2546 | 2547 | ```Ruby 2548 | # bad 2549 | fail RuntimeError, 'message' 2550 | 2551 | # good - signals a RuntimeError by default 2552 | fail 'message' 2553 | ``` 2554 | 2555 | * 2556 | Prefer supplying an exception class and a message as two separate arguments 2557 | to `fail/raise`, instead of an exception instance. 2558 | [[link](#exception-class-messages)] 2559 | 2560 | ```Ruby 2561 | # bad 2562 | fail SomeException.new('message') 2563 | # Note that there is no way to do `fail SomeException.new('message'), backtrace`. 2564 | 2565 | # good 2566 | fail SomeException, 'message' 2567 | # Consistent with `fail SomeException, 'message', backtrace`. 2568 | ``` 2569 | 2570 | * 2571 | Do not return from an `ensure` block. If you explicitly return from a method 2572 | inside an `ensure` block, the return will take precedence over any exception 2573 | being raised, and the method will return as if no exception had been raised at 2574 | all. In effect, the exception will be silently thrown away. 2575 | [[link](#no-return-ensure)] 2576 | 2577 | ```Ruby 2578 | def foo 2579 | fail 2580 | ensure 2581 | return 'very bad idea' 2582 | end 2583 | ``` 2584 | 2585 | * 2586 | Use *implicit begin blocks* where possible. 2587 | [[link](#begin-implicit)] 2588 | 2589 | ```Ruby 2590 | # bad 2591 | def foo 2592 | begin 2593 | # main logic goes here 2594 | rescue 2595 | # failure handling goes here 2596 | end 2597 | end 2598 | 2599 | # good 2600 | def foo 2601 | # main logic goes here 2602 | rescue 2603 | # failure handling goes here 2604 | end 2605 | ``` 2606 | 2607 | * 2608 | Mitigate the proliferation of `begin` blocks by using *contingency methods* 2609 | (a term coined by Avdi Grimm). 2610 | [[link](#contingency-methods)] 2611 | 2612 | ```Ruby 2613 | # bad 2614 | begin 2615 | something_that_might_fail 2616 | rescue IOError 2617 | # handle IOError 2618 | end 2619 | 2620 | begin 2621 | something_else_that_might_fail 2622 | rescue IOError 2623 | # handle IOError 2624 | end 2625 | 2626 | # good 2627 | def with_io_error_handling 2628 | yield 2629 | rescue IOError 2630 | # handle IOError 2631 | end 2632 | 2633 | with_io_error_handling { something_that_might_fail } 2634 | 2635 | with_io_error_handling { something_else_that_might_fail } 2636 | ``` 2637 | 2638 | * 2639 | Don't suppress exceptions. 2640 | [[link](#dont-hide-exceptions)] 2641 | 2642 | ```Ruby 2643 | # bad 2644 | begin 2645 | # an exception occurs here 2646 | rescue SomeError 2647 | # the rescue clause does absolutely nothing 2648 | end 2649 | 2650 | # bad 2651 | do_something rescue nil 2652 | ``` 2653 | 2654 | * 2655 | Avoid using `rescue` in its modifier form. 2656 | [[link](#no-rescue-modifiers)] 2657 | 2658 | ```Ruby 2659 | # bad - this catches exceptions of StandardError class and its descendant classes 2660 | read_file rescue handle_error($!) 2661 | 2662 | # good - this catches only the exceptions of Errno::ENOENT class and its descendant classes 2663 | def foo 2664 | read_file 2665 | rescue Errno::ENOENT => ex 2666 | handle_error(ex) 2667 | end 2668 | ``` 2669 | 2670 | * 2671 | Don't use exceptions for flow of control. 2672 | [[link](#no-exceptional-flows)] 2673 | 2674 | ```Ruby 2675 | # bad 2676 | begin 2677 | n / d 2678 | rescue ZeroDivisionError 2679 | puts 'Cannot divide by 0!' 2680 | end 2681 | 2682 | # good 2683 | if d.zero? 2684 | puts 'Cannot divide by 0!' 2685 | else 2686 | n / d 2687 | end 2688 | ``` 2689 | 2690 | * 2691 | Avoid rescuing the `Exception` class. This will trap signals and calls to 2692 | `exit`, requiring you to `kill -9` the process. 2693 | [[link](#no-blind-rescues)] 2694 | 2695 | ```Ruby 2696 | # bad 2697 | begin 2698 | # calls to exit and kill signals will be caught (except kill -9) 2699 | exit 2700 | rescue Exception 2701 | puts "you didn't really want to exit, right?" 2702 | # exception handling 2703 | end 2704 | 2705 | # good 2706 | begin 2707 | # a blind rescue rescues from StandardError, not Exception as many 2708 | # programmers assume. 2709 | rescue => e 2710 | # exception handling 2711 | end 2712 | 2713 | # also good 2714 | begin 2715 | # an exception occurs here 2716 | 2717 | rescue StandardError => e 2718 | # exception handling 2719 | end 2720 | ``` 2721 | 2722 | * 2723 | Put more specific exceptions higher up the rescue chain, otherwise they'll 2724 | never be rescued from. 2725 | [[link](#exception-ordering)] 2726 | 2727 | ```Ruby 2728 | # bad 2729 | begin 2730 | # some code 2731 | rescue Exception => e 2732 | # some handling 2733 | rescue StandardError => e 2734 | # some handling that will never be executed 2735 | end 2736 | 2737 | # good 2738 | begin 2739 | # some code 2740 | rescue StandardError => e 2741 | # some handling 2742 | rescue Exception => e 2743 | # some handling 2744 | end 2745 | ``` 2746 | 2747 | * 2748 | Release external resources obtained by your program in an `ensure` block. 2749 | [[link](#release-resources)] 2750 | 2751 | ```Ruby 2752 | f = File.open('testfile') 2753 | begin 2754 | # .. process 2755 | rescue 2756 | # .. handle error 2757 | ensure 2758 | f.close if f 2759 | end 2760 | ``` 2761 | 2762 | * 2763 | Use versions of resource obtaining methods that do automatic 2764 | resource cleanup when possible. 2765 | [[link](#auto-release-resources)] 2766 | 2767 | ```Ruby 2768 | # bad - you need to close the file descriptor explicitly 2769 | f = File.open('testfile') 2770 | # ... 2771 | f.close 2772 | 2773 | # good - the file descriptor is closed automatically 2774 | File.open('testfile') do |f| 2775 | # ... 2776 | end 2777 | ``` 2778 | 2779 | * 2780 | Favor the use of exceptions for the standard library over introducing new 2781 | exception classes. 2782 | [[link](#standard-exceptions)] 2783 | 2784 | ## Collections 2785 | 2786 | * 2787 | Prefer literal array and hash creation notation (unless you need to pass 2788 | parameters to their constructors, that is). 2789 | [[link](#literal-array-hash)] 2790 | 2791 | ```Ruby 2792 | # bad 2793 | arr = Array.new 2794 | hash = Hash.new 2795 | 2796 | # good 2797 | arr = [] 2798 | hash = {} 2799 | ``` 2800 | 2801 | * 2802 | Prefer `%w` to the literal array syntax when you need an array of words 2803 | (non-empty strings without spaces and special characters in them). Apply this 2804 | rule only to arrays with two or more elements. 2805 | [[link](#percent-w)] 2806 | 2807 | ```Ruby 2808 | # bad 2809 | STATES = ['draft', 'open', 'closed'] 2810 | 2811 | # good 2812 | STATES = %w(draft open closed) 2813 | ``` 2814 | 2815 | * 2816 | Prefer `%i` to the literal array syntax when you need an array of symbols 2817 | (and you don't need to maintain Ruby 1.9 compatibility). Apply this rule only 2818 | to arrays with two or more elements. 2819 | [[link](#percent-i)] 2820 | 2821 | ```Ruby 2822 | # bad 2823 | STATES = [:draft, :open, :closed] 2824 | 2825 | # good 2826 | STATES = %i(draft open closed) 2827 | ``` 2828 | 2829 | * 2830 | Avoid comma after the last item of an `Array` or `Hash` literal, especially 2831 | when the items are not on separate lines. 2832 | [[link](#no-trailing-array-commas)] 2833 | 2834 | ```Ruby 2835 | # bad - easier to move/add/remove items, but still not preferred 2836 | VALUES = [ 2837 | 1001, 2838 | 2020, 2839 | 3333, 2840 | ] 2841 | 2842 | # bad 2843 | VALUES = [1001, 2020, 3333, ] 2844 | 2845 | # good 2846 | VALUES = [1001, 2020, 3333] 2847 | ``` 2848 | 2849 | * 2850 | Avoid the creation of huge gaps in arrays. 2851 | [[link](#no-gappy-arrays)] 2852 | 2853 | ```Ruby 2854 | arr = [] 2855 | arr[100] = 1 # now you have an array with lots of nils 2856 | ``` 2857 | 2858 | * 2859 | When accessing the first or last element from an array, prefer `first` or 2860 | `last` over `[0]` or `[-1]`. 2861 | [[link](#first-and-last)] 2862 | 2863 | * 2864 | Use `Set` instead of `Array` when dealing with unique elements. `Set` 2865 | implements a collection of unordered values with no duplicates. This is a 2866 | hybrid of `Array`'s intuitive inter-operation facilities and `Hash`'s fast 2867 | lookup. 2868 | [[link](#set-vs-array)] 2869 | 2870 | * 2871 | Prefer symbols instead of strings as hash keys. 2872 | [[link](#symbols-as-keys)] 2873 | 2874 | ```Ruby 2875 | # bad 2876 | hash = { 'one' => 1, 'two' => 2, 'three' => 3 } 2877 | 2878 | # good 2879 | hash = { one: 1, two: 2, three: 3 } 2880 | ``` 2881 | 2882 | * 2883 | Avoid the use of mutable objects as hash keys. 2884 | [[link](#no-mutable-keys)] 2885 | 2886 | * 2887 | Use the Ruby 1.9 hash literal syntax when your hash keys are symbols. 2888 | [[link](#hash-literals)] 2889 | 2890 | ```Ruby 2891 | # bad 2892 | hash = { :one => 1, :two => 2, :three => 3 } 2893 | 2894 | # good 2895 | hash = { one: 1, two: 2, three: 3 } 2896 | ``` 2897 | 2898 | * 2899 | Don't mix the Ruby 1.9 hash syntax with hash rockets in the same hash 2900 | literal. When you've got keys that are not symbols stick to the hash rockets 2901 | syntax. 2902 | [[link](#no-mixed-hash-syntaces)] 2903 | 2904 | ```Ruby 2905 | # bad 2906 | { a: 1, 'b' => 2 } 2907 | 2908 | # good 2909 | { :a => 1, 'b' => 2 } 2910 | ``` 2911 | 2912 | * 2913 | Use `Hash#key?` instead of `Hash#has_key?` and `Hash#value?` instead of 2914 | `Hash#has_value?`. As noted 2915 | [here](http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/43765) by 2916 | Matz, the longer forms are considered deprecated. 2917 | [[link](#hash-key)] 2918 | 2919 | ```Ruby 2920 | # bad 2921 | hash.has_key?(:test) 2922 | hash.has_value?(value) 2923 | 2924 | # good 2925 | hash.key?(:test) 2926 | hash.value?(value) 2927 | ``` 2928 | 2929 | * 2930 | Use `Hash#fetch` when dealing with hash keys that should be present. 2931 | [[link](#hash-fetch)] 2932 | 2933 | ```Ruby 2934 | heroes = { batman: 'Bruce Wayne', superman: 'Clark Kent' } 2935 | # bad - if we make a mistake we might not spot it right away 2936 | heroes[:batman] # => "Bruce Wayne" 2937 | heroes[:supermann] # => nil 2938 | 2939 | # good - fetch raises a KeyError making the problem obvious 2940 | heroes.fetch(:supermann) 2941 | ``` 2942 | 2943 | * 2944 | Introduce default values for hash keys via `Hash#fetch` as opposed to using 2945 | custom logic. 2946 | [[link](#hash-fetch-defaults)] 2947 | 2948 | ```Ruby 2949 | batman = { name: 'Bruce Wayne', is_evil: false } 2950 | 2951 | # bad - if we just use || operator with falsy value we won't get the expected result 2952 | batman[:is_evil] || true # => true 2953 | 2954 | # good - fetch work correctly with falsy values 2955 | batman.fetch(:is_evil, true) # => false 2956 | ``` 2957 | 2958 | * 2959 | Prefer the use of the block instead of the default value in `Hash#fetch`. 2960 | [[link](#use-hash-blocks)] 2961 | 2962 | ```Ruby 2963 | batman = { name: 'Bruce Wayne' } 2964 | 2965 | # bad - if we use the default value, we eager evaluate it 2966 | # so it can slow the program down if done multiple times 2967 | batman.fetch(:powers, get_batman_powers) # get_batman_powers is an expensive call 2968 | 2969 | # good - blocks are lazy evaluated, so only triggered in case of KeyError exception 2970 | batman.fetch(:powers) { get_batman_powers } 2971 | ``` 2972 | 2973 | * 2974 | Use `Hash#values_at` when you need to retrieve several values consecutively 2975 | from a hash. 2976 | [[link](#hash-values-at)] 2977 | 2978 | ```Ruby 2979 | # bad 2980 | email = data['email'] 2981 | username = data['nickname'] 2982 | 2983 | # good 2984 | email, username = data.values_at('email', 'nickname') 2985 | ``` 2986 | 2987 | * 2988 | Rely on the fact that as of Ruby 1.9 hashes are ordered. 2989 | [[link](#ordered-hashes)] 2990 | 2991 | * 2992 | Do not modify a collection while traversing it. 2993 | [[link](#no-modifying-collections)] 2994 | 2995 | * 2996 | When accessing elements of a collection, avoid direct access 2997 | via `[n]` by using an alternate form of the reader method if it is 2998 | supplied. This guards you from calling `[]` on `nil`. 2999 | [[link](#accessing-elements-directly)] 3000 | 3001 | ```Ruby 3002 | # bad 3003 | Regexp.last_match[1] 3004 | 3005 | # good 3006 | Regexp.last_match(1) 3007 | ``` 3008 | 3009 | * 3010 | When providing an accessor for a collection, provide an alternate form 3011 | to save users from checking for `nil` before accessing an element in 3012 | the collection. 3013 | [[link](#provide-alternate-accessor-to-collections)] 3014 | 3015 | ```Ruby 3016 | # bad 3017 | def awesome_things 3018 | @awesome_things 3019 | end 3020 | 3021 | # good 3022 | def awesome_things(index = nil) 3023 | if index && @awesome_things 3024 | @awesome_things[index] 3025 | else 3026 | @awesome_things 3027 | end 3028 | end 3029 | ``` 3030 | 3031 | ## Strings 3032 | 3033 | * 3034 | Prefer string interpolation and string formatting instead of string 3035 | concatenation: 3036 | [[link](#string-interpolation)] 3037 | 3038 | ```Ruby 3039 | # bad 3040 | email_with_name = user.name + ' <' + user.email + '>' 3041 | 3042 | # good 3043 | email_with_name = "#{user.name} <#{user.email}>" 3044 | 3045 | # good 3046 | email_with_name = format('%s <%s>', user.name, user.email) 3047 | ``` 3048 | 3049 | * 3050 | Consider padding string interpolation code with space. It more clearly sets 3051 | the code apart from the string. 3052 | [[link](#pad-string-interpolation)] 3053 | 3054 | ```Ruby 3055 | "#{ user.last_name }, #{ user.first_name }" 3056 | ``` 3057 | 3058 | * 3059 | Adopt a consistent string literal quoting style. There are two popular 3060 | styles in the Ruby community, both of which are considered good - single 3061 | quotes by default (Option A) and double quotes by default (Option B). 3062 | [[link](#consistent-string-literals)] 3063 | 3064 | * **(Option A)** Prefer single-quoted strings when you don't need 3065 | string interpolation or special symbols such as `\t`, `\n`, `'`, 3066 | etc. 3067 | 3068 | ```Ruby 3069 | # bad 3070 | name = "Bozhidar" 3071 | 3072 | # good 3073 | name = 'Bozhidar' 3074 | ``` 3075 | 3076 | * **(Option B)** Prefer double-quotes unless your string literal 3077 | contains `"` or escape characters you want to suppress. 3078 | 3079 | ```Ruby 3080 | # bad 3081 | name = 'Bozhidar' 3082 | 3083 | # good 3084 | name = "Bozhidar" 3085 | ``` 3086 | 3087 | The string literals in this guide are aligned with the first style. 3088 | 3089 | * 3090 | Don't use the character literal syntax `?x`. Since Ruby 1.9 it's basically 3091 | redundant - `?x` would interpreted as `'x'` (a string with a single character 3092 | in it). 3093 | [[link](#no-character-literals)] 3094 | 3095 | ```Ruby 3096 | # bad 3097 | char = ?c 3098 | 3099 | # good 3100 | char = 'c' 3101 | ``` 3102 | 3103 | * 3104 | Don't leave out `{}` around instance and global variables being interpolated 3105 | into a string. 3106 | [[link](#curlies-interpolate)] 3107 | 3108 | ```Ruby 3109 | class Person 3110 | attr_reader :first_name, :last_name 3111 | 3112 | def initialize(first_name, last_name) 3113 | @first_name = first_name 3114 | @last_name = last_name 3115 | end 3116 | 3117 | # bad - valid, but awkward 3118 | def to_s 3119 | "#@first_name #@last_name" 3120 | end 3121 | 3122 | # good 3123 | def to_s 3124 | "#{@first_name} #{@last_name}" 3125 | end 3126 | end 3127 | 3128 | $global = 0 3129 | # bad 3130 | puts "$global = #$global" 3131 | 3132 | # good 3133 | puts "$global = #{$global}" 3134 | ``` 3135 | 3136 | * 3137 | Don't use `Object#to_s` on interpolated objects. It's invoked on them 3138 | automatically. 3139 | [[link](#no-to-s)] 3140 | 3141 | ```Ruby 3142 | # bad 3143 | message = "This is the #{result.to_s}." 3144 | 3145 | # good 3146 | message = "This is the #{result}." 3147 | ``` 3148 | 3149 | * 3150 | Avoid using `String#+` when you need to construct large data chunks. 3151 | Instead, use `String#<<`. Concatenation mutates the string instance in-place 3152 | and is always faster than `String#+`, which creates a bunch of new string 3153 | objects. 3154 | [[link](#concat-strings)] 3155 | 3156 | ```Ruby 3157 | # good and also fast 3158 | html = '' 3159 | html << '

Page title

' 3160 | 3161 | paragraphs.each do |paragraph| 3162 | html << "

#{paragraph}

" 3163 | end 3164 | ``` 3165 | 3166 | * 3167 | Don't use `String#gsub` in scenarios in which you can use a faster more specialized alternative. 3168 | [[link](#dont-abuse-gsub)] 3169 | 3170 | ```Ruby 3171 | url = 'http://example.com' 3172 | str = 'lisp-case-rules' 3173 | 3174 | # bad 3175 | url.gsub("http://", "https://") 3176 | str.gsub("-", "_") 3177 | 3178 | # good 3179 | url.sub("http://", "https://") 3180 | str.tr("-", "_") 3181 | ``` 3182 | 3183 | * 3184 | When using heredocs for multi-line strings keep in mind the fact that they 3185 | preserve leading whitespace. It's a good practice to employ some margin based 3186 | on which to trim the excessive whitespace. 3187 | [[link](#heredocs)] 3188 | 3189 | ```Ruby 3190 | code = <<-END.gsub(/^\s+\|/, '') 3191 | |def test 3192 | | some_method 3193 | | other_method 3194 | |end 3195 | END 3196 | # => "def test\n some_method\n other_method\nend\n" 3197 | ``` 3198 | 3199 | ## Regular Expressions 3200 | 3201 | > Some people, when confronted with a problem, think 3202 | > "I know, I'll use regular expressions." Now they have two problems.
3203 | > -- Jamie Zawinski 3204 | 3205 | * 3206 | Don't use regular expressions if you just need plain text search in string: 3207 | `string['text']` 3208 | [[link](#no-regexp-for-plaintext)] 3209 | 3210 | * 3211 | For simple constructions you can use regexp directly through string index. 3212 | [[link](#regexp-string-index)] 3213 | 3214 | ```Ruby 3215 | match = string[/regexp/] # get content of matched regexp 3216 | first_group = string[/text(grp)/, 1] # get content of captured group 3217 | string[/text (grp)/, 1] = 'replace' # string => 'text replace' 3218 | ``` 3219 | 3220 | * 3221 | Use non-capturing groups when you don't use captured result of parentheses. 3222 | [[link](#non-capturing-regexp)] 3223 | 3224 | ```Ruby 3225 | /(first|second)/ # bad 3226 | /(?:first|second)/ # good 3227 | ``` 3228 | 3229 | * 3230 | Don't use the cryptic Perl-legacy variables denoting last regexp group 3231 | matches (`$1`, `$2`, etc). Use `Regexp.last_match(n)` instead. 3232 | [[link](#no-perl-regexp-last-matchers)] 3233 | 3234 | ```Ruby 3235 | /(regexp)/ =~ string 3236 | ... 3237 | 3238 | # bad 3239 | process $1 3240 | 3241 | # good 3242 | process Regexp.last_match(1) 3243 | ``` 3244 | 3245 | * 3246 | Avoid using numbered groups as it can be hard to track what they contain. 3247 | Named groups can be used instead. 3248 | [[link](#no-numbered-regexes)] 3249 | 3250 | ```Ruby 3251 | # bad 3252 | /(regexp)/ =~ string 3253 | ... 3254 | process Regexp.last_match(1) 3255 | 3256 | # good 3257 | /(?regexp)/ =~ string 3258 | ... 3259 | process meaningful_var 3260 | ``` 3261 | 3262 | * 3263 | Character classes have only a few special characters you should care about: 3264 | `^`, `-`, `\`, `]`, so don't escape `.` or brackets in `[]`. 3265 | [[link](#limit-escapes)] 3266 | 3267 | * 3268 | Be careful with `^` and `$` as they match start/end of line, not string 3269 | endings. If you want to match the whole string use: `\A` and `\z` (not to be 3270 | confused with `\Z` which is the equivalent of `/\n?\z/`). 3271 | [[link](#caret-and-dollar-regexp)] 3272 | 3273 | ```Ruby 3274 | string = "some injection\nusername" 3275 | string[/^username$/] # matches 3276 | string[/\Ausername\z/] # doesn't match 3277 | ``` 3278 | 3279 | * 3280 | Use `x` modifier for complex regexps. This makes them more readable and you 3281 | can add some useful comments. Just be careful as spaces are ignored. 3282 | [[link](#comment-regexes)] 3283 | 3284 | ```Ruby 3285 | regexp = / 3286 | start # some text 3287 | \s # white space char 3288 | (group) # first group 3289 | (?:alt1|alt2) # some alternation 3290 | end 3291 | /x 3292 | ``` 3293 | 3294 | * 3295 | For complex replacements `sub`/`gsub` can be used with block or hash. 3296 | [[link](#gsub-blocks)] 3297 | 3298 | ## Percent Literals 3299 | 3300 | * 3301 | Use `%()`(it's a shorthand for `%Q`) for single-line strings which require 3302 | both interpolation and embedded double-quotes. For multi-line strings, prefer 3303 | heredocs. 3304 | [[link](#percent-q-shorthand)] 3305 | 3306 | ```Ruby 3307 | # bad (no interpolation needed) 3308 | %(
Some text
) 3309 | # should be '
Some text
' 3310 | 3311 | # bad (no double-quotes) 3312 | %(This is #{quality} style) 3313 | # should be "This is #{quality} style" 3314 | 3315 | # bad (multiple lines) 3316 | %(
\n#{exclamation}\n
) 3317 | # should be a heredoc. 3318 | 3319 | # good (requires interpolation, has quotes, single line) 3320 | %(#{name}) 3321 | ``` 3322 | 3323 | * 3324 | Avoid `%q` unless you have a string with both `'` and `"` in it. Regular 3325 | string literals are more readable and should be preferred unless a lot of 3326 | characters would have to be escaped in them. 3327 | [[link](#percent-q)] 3328 | 3329 | ```Ruby 3330 | # bad 3331 | name = %q(Bruce Wayne) 3332 | time = %q(8 o'clock) 3333 | question = %q("What did you say?") 3334 | 3335 | # good 3336 | name = 'Bruce Wayne' 3337 | time = "8 o'clock" 3338 | question = '"What did you say?"' 3339 | ``` 3340 | 3341 | * 3342 | Use `%r` only for regular expressions matching *at least* one '/' 3343 | character. 3344 | [[link](#percent-r)] 3345 | 3346 | ```Ruby 3347 | # bad 3348 | %r{\s+} 3349 | 3350 | # good 3351 | %r{^/(.*)$} 3352 | %r{^/blog/2011/(.*)$} 3353 | ``` 3354 | 3355 | * 3356 | Avoid the use of `%x` unless you're going to invoke a command with 3357 | backquotes in it(which is rather unlikely). 3358 | [[link](#percent-x)] 3359 | 3360 | ```Ruby 3361 | # bad 3362 | date = %x(date) 3363 | 3364 | # good 3365 | date = `date` 3366 | echo = %x(echo `date`) 3367 | ``` 3368 | 3369 | * 3370 | Avoid the use of `%s`. It seems that the community has decided `:"some 3371 | string"` is the preferred way to create a symbol with spaces in it. 3372 | [[link](#percent-s)] 3373 | 3374 | * 3375 | Prefer `()` as delimiters for all `%` literals, except `%r`. Since parentheses 3376 | often appear inside regular expressions in many scenarios a less common 3377 | character like `{` might be a better choice for a delimiter, depending on the 3378 | regexp's content. 3379 | [[link](#percent-literal-braces)] 3380 | 3381 | ```Ruby 3382 | # bad 3383 | %w[one two three] 3384 | %q{"Test's king!", John said.} 3385 | 3386 | # good 3387 | %w(one two three) 3388 | %q("Test's king!", John said.) 3389 | ``` 3390 | 3391 | ## Metaprogramming 3392 | 3393 | * 3394 | Avoid needless metaprogramming. 3395 | [[link](#no-needless-metaprogramming)] 3396 | 3397 | * 3398 | Do not mess around in core classes when writing libraries. (Do not 3399 | monkey-patch them.) 3400 | [[link](#no-monkey-patching)] 3401 | 3402 | * 3403 | The block form of `class_eval` is preferable to the string-interpolated 3404 | form. - when you use the string-interpolated form, always supply `__FILE__` 3405 | and `__LINE__`, so that your backtraces make sense: 3406 | [[link](#block-class-eval)] 3407 | 3408 | ```ruby 3409 | class_eval 'def use_relative_model_naming?; true; end', __FILE__, __LINE__ 3410 | ``` 3411 | 3412 | - `define_method` is preferable to `class_eval{ def ... }` 3413 | 3414 | * 3415 | When using `class_eval` (or other `eval`) with string interpolation, add a 3416 | comment block showing its appearance if interpolated (a practice used in Rails 3417 | code): 3418 | [[link](#eval-comment-docs)] 3419 | 3420 | ```ruby 3421 | # from activesupport/lib/active_support/core_ext/string/output_safety.rb 3422 | UNSAFE_STRING_METHODS.each do |unsafe_method| 3423 | if 'String'.respond_to?(unsafe_method) 3424 | class_eval <<-EOT, __FILE__, __LINE__ + 1 3425 | def #{unsafe_method}(*params, &block) # def capitalize(*params, &block) 3426 | to_str.#{unsafe_method}(*params, &block) # to_str.capitalize(*params, &block) 3427 | end # end 3428 | 3429 | def #{unsafe_method}!(*params) # def capitalize!(*params) 3430 | @dirty = true # @dirty = true 3431 | super # super 3432 | end # end 3433 | EOT 3434 | end 3435 | end 3436 | ``` 3437 | 3438 | * 3439 | Avoid using `method_missing` for metaprogramming because backtraces become 3440 | messy, the behavior is not listed in `#methods`, and misspelled method calls 3441 | might silently work, e.g. `nukes.launch_state = false`. Consider using 3442 | delegation, proxy, or `define_method` instead. If you must use 3443 | `method_missing`: 3444 | [[link](#no-method-missing)] 3445 | 3446 | - Be sure to [also define `respond_to_missing?`](http://blog.marc-andre.ca/2010/11/methodmissing-politely.html) 3447 | - Only catch methods with a well-defined prefix, such as `find_by_*` -- make your code as assertive as possible. 3448 | - Call `super` at the end of your statement 3449 | - Delegate to assertive, non-magical methods: 3450 | 3451 | ```ruby 3452 | # bad 3453 | def method_missing?(meth, *params, &block) 3454 | if /^find_by_(?.*)/ =~ meth 3455 | # ... lots of code to do a find_by 3456 | else 3457 | super 3458 | end 3459 | end 3460 | 3461 | # good 3462 | def method_missing?(meth, *params, &block) 3463 | if /^find_by_(?.*)/ =~ meth 3464 | find_by(prop, *params, &block) 3465 | else 3466 | super 3467 | end 3468 | end 3469 | 3470 | # best of all, though, would to define_method as each findable attribute is declared 3471 | ``` 3472 | 3473 | * 3474 | Prefer `public_send` over `send` so as not to circumvent `private`/`protected` visibility. 3475 | [[link](#prefer-public-send)] 3476 | 3477 | ## Misc 3478 | 3479 | * 3480 | Write `ruby -w` safe code. 3481 | [[link](#always-warn)] 3482 | 3483 | * 3484 | Avoid hashes as optional parameters. Does the method do too much? (Object 3485 | initializers are exceptions for this rule). 3486 | [[link](#no-optional-hash-params)] 3487 | 3488 | * 3489 | Avoid methods longer than 10 LOC (lines of code). Ideally, most methods will 3490 | be shorter than 5 LOC. Empty lines do not contribute to the relevant LOC. 3491 | [[link](#short-methods)] 3492 | 3493 | * 3494 | Avoid parameter lists longer than three or four parameters. 3495 | [[link](#too-many-params)] 3496 | 3497 | * 3498 | If you really need "global" methods, add them to Kernel and make them 3499 | private. 3500 | [[link](#private-global-methods)] 3501 | 3502 | * 3503 | Use module instance variables instead of global variables. 3504 | [[link](#instance-vars)] 3505 | 3506 | ```Ruby 3507 | # bad 3508 | $foo_bar = 1 3509 | 3510 | # good 3511 | module Foo 3512 | class << self 3513 | attr_accessor :bar 3514 | end 3515 | end 3516 | 3517 | Foo.bar = 1 3518 | ``` 3519 | 3520 | * 3521 | Use `OptionParser` for parsing complex command line options and `ruby -s` 3522 | for trivial command line options. 3523 | [[link](#optionparser)] 3524 | 3525 | * 3526 | Prefer `Time.now` over `Time.new` when retrieving the current system time. 3527 | [[link](#time-now)] 3528 | 3529 | * 3530 | Code in a functional way, avoiding mutation when that makes sense. 3531 | [[link](#functional-code)] 3532 | 3533 | * 3534 | Do not mutate parameters unless that is the purpose of the method. 3535 | [[link](#no-param-mutations)] 3536 | 3537 | * 3538 | Avoid more than three levels of block nesting. 3539 | [[link](#three-is-the-number-thou-shalt-count)] 3540 | 3541 | * 3542 | Be consistent. In an ideal world, be consistent with these guidelines. 3543 | [[link](#be-consistent)] 3544 | 3545 | * 3546 | Use common sense. 3547 | [[link](#common-sense)] 3548 | 3549 | ## Tools 3550 | 3551 | Here's some tools to help you automatically check Ruby code against 3552 | this guide. 3553 | 3554 | ### RuboCop 3555 | 3556 | [RuboCop][] is a Ruby code style 3557 | checker based on this style guide. RuboCop already covers a 3558 | significant portion of the Guide, supports both MRI 1.9 and MRI 2.0 3559 | and has good Emacs integration. 3560 | 3561 | ### RubyMine 3562 | 3563 | [RubyMine](http://www.jetbrains.com/ruby/)'s code inspections are 3564 | [partially based](http://confluence.jetbrains.com/display/RUBYDEV/RubyMine+Inspections) 3565 | on this guide. 3566 | 3567 | # Contributing 3568 | 3569 | The guide is still a work in progress - some rules are lacking examples, some 3570 | rules don't have examples that illustrate them clearly enough. Improving such rules 3571 | is a great (and simple way) to help the Ruby community! 3572 | 3573 | In due time these issues will (hopefully) be addressed - just keep them in mind 3574 | for now. 3575 | 3576 | Nothing written in this guide is set in stone. It's my desire to work 3577 | together with everyone interested in Ruby coding style, so that we could 3578 | ultimately create a resource that will be beneficial to the entire Ruby 3579 | community. 3580 | 3581 | Feel free to open tickets or send pull requests with improvements. Thanks in 3582 | advance for your help! 3583 | 3584 | You can also support the project (and RuboCop) with financial 3585 | contributions via [gittip](https://www.gittip.com/bbatsov). 3586 | 3587 | [![Support via Gittip](https://rawgithub.com/twolfson/gittip-badge/0.2.0/dist/gittip.png)](https://www.gittip.com/bbatsov) 3588 | 3589 | ## How to Contribute? 3590 | 3591 | It's easy, just follow the [contribution guidelines](https://github.com/bbatsov/ruby-style-guide/blob/master/CONTRIBUTING.md). 3592 | 3593 | # License 3594 | 3595 | ![Creative Commons License](http://i.creativecommons.org/l/by/3.0/88x31.png) 3596 | This work is licensed under a [Creative Commons Attribution 3.0 Unported License](http://creativecommons.org/licenses/by/3.0/deed.en_US) 3597 | 3598 | # Spread the Word 3599 | 3600 | A community-driven style guide is of little use to a community that 3601 | doesn't know about its existence. Tweet about the guide, share it with 3602 | your friends and colleagues. Every comment, suggestion or opinion we 3603 | get makes the guide just a little bit better. And we want to have the 3604 | best possible guide, don't we? 3605 | 3606 | Cheers,
3607 | [Bozhidar](https://twitter.com/bbatsov) 3608 | 3609 | [PEP-8]: http://www.python.org/dev/peps/pep-0008/ 3610 | [rails-style-guide]: https://github.com/bbatsov/rails-style-guide 3611 | [pickaxe]: http://pragprog.com/book/ruby4/programming-ruby-1-9-2-0 3612 | [trpl]: http://www.amazon.com/Ruby-Programming-Language-David-Flanagan/dp/0596516177 3613 | [transmuter]: https://github.com/TechnoGate/transmuter 3614 | [RuboCop]: https://github.com/bbatsov/rubocop 3615 | --------------------------------------------------------------------------------