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

Page title

' 3732 | 3733 | paragraphs.each do |paragraph| 3734 | html += "

#{paragraph}

" 3735 | end 3736 | 3737 | # good and also fast 3738 | html = '' 3739 | html << '

Page title

' 3740 | 3741 | paragraphs.each do |paragraph| 3742 | html << "

#{paragraph}

" 3743 | end 3744 | ``` 3745 | 3746 | * 3747 | Don't use `String#gsub` in scenarios in which you can use a faster more specialized alternative. 3748 | [[link](#dont-abuse-gsub)] 3749 | 3750 | ```Ruby 3751 | url = 'http://example.com' 3752 | str = 'lisp-case-rules' 3753 | 3754 | # bad 3755 | url.gsub('http://', 'https://') 3756 | str.gsub('-', '_') 3757 | 3758 | # good 3759 | url.sub('http://', 'https://') 3760 | str.tr('-', '_') 3761 | ``` 3762 | 3763 | * 3764 | When using heredocs for multi-line strings keep in mind the fact that they 3765 | preserve leading whitespace. It's a good practice to employ some margin based 3766 | on which to trim the excessive whitespace. 3767 | [[link](#heredocs)] 3768 | 3769 | ```Ruby 3770 | code = <<-END.gsub(/^\s+\|/, '') 3771 | |def test 3772 | | some_method 3773 | | other_method 3774 | |end 3775 | END 3776 | # => "def test\n some_method\n other_method\nend\n" 3777 | ``` 3778 | 3779 | * 3780 | Use Ruby 2.3's squiggly heredocs for nicely indented multi-line strings. 3781 | [[link](#squiggly-heredocs)] 3782 | 3783 | ```Ruby 3784 | # bad - using Powerpack String#strip_margin 3785 | code = <<-END.strip_margin('|') 3786 | |def test 3787 | | some_method 3788 | | other_method 3789 | |end 3790 | END 3791 | 3792 | # also bad 3793 | code = <<-END 3794 | def test 3795 | some_method 3796 | other_method 3797 | end 3798 | END 3799 | 3800 | # good 3801 | code = <<~END 3802 | def test 3803 | some_method 3804 | other_method 3805 | end 3806 | END 3807 | ``` 3808 | 3809 | ## Date & Time 3810 | 3811 | * 3812 | Prefer `Time.now` over `Time.new` when retrieving the current system time. 3813 | [[link](#time-now)] 3814 | 3815 | * 3816 | Don't use `DateTime` unless you need to account for historical calendar 3817 | reform -- and if you do, explicitly specify the `start` argument to 3818 | clearly state your intentions. 3819 | [[link](#no-datetime)] 3820 | 3821 | ```Ruby 3822 | # bad - uses DateTime for current time 3823 | DateTime.now 3824 | 3825 | # good - uses Time for current time 3826 | Time.now 3827 | 3828 | # bad - uses DateTime for modern date 3829 | DateTime.iso8601('2016-06-29') 3830 | 3831 | # good - uses Date for modern date 3832 | Date.iso8601('2016-06-29') 3833 | 3834 | # good - uses DateTime with start argument for historical date 3835 | DateTime.iso8601('1751-04-23', Date::ENGLAND) 3836 | ``` 3837 | 3838 | ## Regular Expressions 3839 | 3840 | > Some people, when confronted with a problem, think 3841 | > "I know, I'll use regular expressions." Now they have two problems.
3842 | > -- Jamie Zawinski 3843 | 3844 | * 3845 | Don't use regular expressions if you just need plain text search in string: 3846 | `string['text']` 3847 | [[link](#no-regexp-for-plaintext)] 3848 | 3849 | * 3850 | For simple constructions you can use regexp directly through string index. 3851 | [[link](#regexp-string-index)] 3852 | 3853 | ```Ruby 3854 | match = string[/regexp/] # get content of matched regexp 3855 | first_group = string[/text(grp)/, 1] # get content of captured group 3856 | string[/text (grp)/, 1] = 'replace' # string => 'text replace' 3857 | ``` 3858 | 3859 | * 3860 | Use non-capturing groups when you don't use the captured result. 3861 | [[link](#non-capturing-regexp)] 3862 | 3863 | ```Ruby 3864 | # bad 3865 | /(first|second)/ 3866 | 3867 | # good 3868 | /(?:first|second)/ 3869 | ``` 3870 | 3871 | * 3872 | Don't use the cryptic Perl-legacy variables denoting last regexp group 3873 | matches (`$1`, `$2`, etc). Use `Regexp.last_match(n)` instead. 3874 | [[link](#no-perl-regexp-last-matchers)] 3875 | 3876 | ```Ruby 3877 | /(regexp)/ =~ string 3878 | ... 3879 | 3880 | # bad 3881 | process $1 3882 | 3883 | # good 3884 | process Regexp.last_match(1) 3885 | ``` 3886 | 3887 | * 3888 | Avoid using numbered groups as it can be hard to track what they contain. 3889 | Named groups can be used instead. 3890 | [[link](#no-numbered-regexes)] 3891 | 3892 | ```Ruby 3893 | # bad 3894 | /(regexp)/ =~ string 3895 | # some code 3896 | process Regexp.last_match(1) 3897 | 3898 | # good 3899 | /(?regexp)/ =~ string 3900 | # some code 3901 | process meaningful_var 3902 | ``` 3903 | 3904 | * 3905 | Character classes have only a few special characters you should care about: 3906 | `^`, `-`, `\`, `]`, so don't escape `.` or brackets in `[]`. 3907 | [[link](#limit-escapes)] 3908 | 3909 | * 3910 | Be careful with `^` and `$` as they match start/end of line, not string 3911 | endings. If you want to match the whole string use: `\A` and `\z` (not to be 3912 | confused with `\Z` which is the equivalent of `/\n?\z/`). 3913 | [[link](#caret-and-dollar-regexp)] 3914 | 3915 | ```Ruby 3916 | string = "some injection\nusername" 3917 | string[/^username$/] # matches 3918 | string[/\Ausername\z/] # doesn't match 3919 | ``` 3920 | 3921 | * 3922 | Use `x` modifier for complex regexps. This makes them more readable and you 3923 | can add some useful comments. Just be careful as spaces are ignored. 3924 | [[link](#comment-regexes)] 3925 | 3926 | ```Ruby 3927 | regexp = / 3928 | start # some text 3929 | \s # white space char 3930 | (group) # first group 3931 | (?:alt1|alt2) # some alternation 3932 | end 3933 | /x 3934 | ``` 3935 | 3936 | * 3937 | For complex replacements `sub`/`gsub` can be used with a block or a hash. 3938 | [[link](#gsub-blocks)] 3939 | 3940 | ```Ruby 3941 | words = 'foo bar' 3942 | words.sub(/f/, 'f' => 'F') # => 'Foo bar' 3943 | words.gsub(/\w+/) { |word| word.capitalize } # => 'Foo Bar' 3944 | ``` 3945 | 3946 | ## Percent Literals 3947 | 3948 | * 3949 | Use `%()`(it's a shorthand for `%Q`) for single-line strings which require 3950 | both interpolation and embedded double-quotes. For multi-line strings, prefer 3951 | heredocs. 3952 | [[link](#percent-q-shorthand)] 3953 | 3954 | ```Ruby 3955 | # bad (no interpolation needed) 3956 | %(
Some text
) 3957 | # should be '
Some text
' 3958 | 3959 | # bad (no double-quotes) 3960 | %(This is #{quality} style) 3961 | # should be "This is #{quality} style" 3962 | 3963 | # bad (multiple lines) 3964 | %(
\n#{exclamation}\n
) 3965 | # should be a heredoc. 3966 | 3967 | # good (requires interpolation, has quotes, single line) 3968 | %(#{name}) 3969 | ``` 3970 | 3971 | * 3972 | Avoid %() or the equivalent %q() unless you have a string with both `'` and 3973 | `"` in it. Regular string literals are more readable and should be preferred 3974 | unless a lot of characters would have to be escaped in them. 3975 | [[link](#percent-q)] 3976 | 3977 | ```Ruby 3978 | # bad 3979 | name = %q(Bruce Wayne) 3980 | time = %q(8 o'clock) 3981 | question = %q("What did you say?") 3982 | 3983 | # good 3984 | name = 'Bruce Wayne' 3985 | time = "8 o'clock" 3986 | question = '"What did you say?"' 3987 | quote = %q(

"What did you say?"

) 3988 | ``` 3989 | 3990 | * 3991 | Use `%r` only for regular expressions matching *at least* one '/' 3992 | character. 3993 | [[link](#percent-r)] 3994 | 3995 | ```Ruby 3996 | # bad 3997 | %r{\s+} 3998 | 3999 | # good 4000 | %r{^/(.*)$} 4001 | %r{^/blog/2011/(.*)$} 4002 | ``` 4003 | 4004 | * 4005 | Avoid the use of `%x` unless you're going to invoke a command with 4006 | backquotes in it(which is rather unlikely). 4007 | [[link](#percent-x)] 4008 | 4009 | ```Ruby 4010 | # bad 4011 | date = %x(date) 4012 | 4013 | # good 4014 | date = `date` 4015 | echo = %x(echo `date`) 4016 | ``` 4017 | 4018 | * 4019 | Avoid the use of `%s`. It seems that the community has decided `:"some 4020 | string"` is the preferred way to create a symbol with spaces in it. 4021 | [[link](#percent-s)] 4022 | 4023 | * 4024 | Use the braces that are the most appropriate for the various kinds of percent 4025 | literals. 4026 | [[link](#percent-literal-braces)] 4027 | - `()` for string literals(`%q`, `%Q`). 4028 | - `[]` for array literals(`%w`, `%i`, `%W`, `%I`) as it is aligned with 4029 | the standard array literals. 4030 | - `{}` for regexp literals(`%r`) since parentheses often appear inside regular 4031 | expressions. That's why a less common character with `{` is usually the best 4032 | delimiter for `%r` literals. 4033 | - `()` for all other literals (e.g. `%s`, `%x`) 4034 | 4035 | ```Ruby 4036 | # bad 4037 | %q{"Test's king!", John said.} 4038 | 4039 | # good 4040 | %q("Test's king!", John said.) 4041 | 4042 | # bad 4043 | %w(one two three) 4044 | %i(one two three) 4045 | 4046 | # good 4047 | %w[one two three] 4048 | %i[one two three] 4049 | 4050 | # bad 4051 | %r((\w+)-(\d+)) 4052 | %r{\w{1,2}\d{2,5}} 4053 | 4054 | # good 4055 | %r{(\w+)-(\d+)} 4056 | %r|\w{1,2}\d{2,5}| 4057 | ``` 4058 | 4059 | ## Metaprogramming 4060 | 4061 | * 4062 | Avoid needless metaprogramming. 4063 | [[link](#no-needless-metaprogramming)] 4064 | 4065 | * 4066 | Do not mess around in core classes when writing libraries. (Do not 4067 | monkey-patch them.) 4068 | [[link](#no-monkey-patching)] 4069 | 4070 | * 4071 | The block form of `class_eval` is preferable to the string-interpolated 4072 | form. 4073 | [[link](#block-class-eval)] 4074 | 4075 | - when you use the string-interpolated form, always supply `__FILE__` 4076 | and `__LINE__`, so that your backtraces make sense: 4077 | 4078 | ```ruby 4079 | class_eval 'def use_relative_model_naming?; true; end', __FILE__, __LINE__ 4080 | ``` 4081 | 4082 | - `define_method` is preferable to `class_eval{ def ... }` 4083 | 4084 | * 4085 | When using `class_eval` (or other `eval`) with string interpolation, add a 4086 | comment block showing its appearance if interpolated (a practice used in Rails 4087 | code): 4088 | [[link](#eval-comment-docs)] 4089 | 4090 | ```ruby 4091 | # from activesupport/lib/active_support/core_ext/string/output_safety.rb 4092 | UNSAFE_STRING_METHODS.each do |unsafe_method| 4093 | if 'String'.respond_to?(unsafe_method) 4094 | class_eval <<-EOT, __FILE__, __LINE__ + 1 4095 | def #{unsafe_method}(*params, &block) # def capitalize(*params, &block) 4096 | to_str.#{unsafe_method}(*params, &block) # to_str.capitalize(*params, &block) 4097 | end # end 4098 | 4099 | def #{unsafe_method}!(*params) # def capitalize!(*params) 4100 | @dirty = true # @dirty = true 4101 | super # super 4102 | end # end 4103 | EOT 4104 | end 4105 | end 4106 | ``` 4107 | 4108 | * 4109 | Avoid using `method_missing` for metaprogramming because backtraces become 4110 | messy, the behavior is not listed in `#methods`, and misspelled method calls 4111 | might silently work, e.g. `nukes.launch_state = false`. Consider using 4112 | delegation, proxy, or `define_method` instead. If you must use 4113 | `method_missing`: 4114 | [[link](#no-method-missing)] 4115 | 4116 | - Be sure to [also define `respond_to_missing?`](http://blog.marc-andre.ca/2010/11/methodmissing-politely.html) 4117 | - Only catch methods with a well-defined prefix, such as `find_by_*` -- make your code as assertive as possible. 4118 | - Call `super` at the end of your statement 4119 | - Delegate to assertive, non-magical methods: 4120 | 4121 | ```ruby 4122 | # bad 4123 | def method_missing?(meth, *params, &block) 4124 | if /^find_by_(?.*)/ =~ meth 4125 | # ... lots of code to do a find_by 4126 | else 4127 | super 4128 | end 4129 | end 4130 | 4131 | # good 4132 | def method_missing?(meth, *params, &block) 4133 | if /^find_by_(?.*)/ =~ meth 4134 | find_by(prop, *params, &block) 4135 | else 4136 | super 4137 | end 4138 | end 4139 | 4140 | # best of all, though, would to define_method as each findable attribute is declared 4141 | ``` 4142 | 4143 | * 4144 | Prefer `public_send` over `send` so as not to circumvent `private`/`protected` visibility. 4145 | [[link](#prefer-public-send)] 4146 | 4147 | ```ruby 4148 | # We have an ActiveModel Organization that includes concern Activatable 4149 | module Activatable 4150 | extend ActiveSupport::Concern 4151 | 4152 | included do 4153 | before_create :create_token 4154 | end 4155 | 4156 | private 4157 | 4158 | def reset_token 4159 | # some code 4160 | end 4161 | 4162 | def create_token 4163 | # some code 4164 | end 4165 | 4166 | def activate! 4167 | # some code 4168 | end 4169 | end 4170 | 4171 | class Organization < ActiveRecord::Base 4172 | include Activatable 4173 | end 4174 | 4175 | linux_organization = Organization.find(...) 4176 | # BAD - violates privacy 4177 | linux_organization.send(:reset_token) 4178 | # GOOD - should throw an exception 4179 | linux_organization.public_send(:reset_token) 4180 | ``` 4181 | 4182 | * 4183 | Prefer `__send__` over `send`, as `send` may overlap with existing methods. 4184 | [[link](#prefer-__send__)] 4185 | 4186 | ```ruby 4187 | require 'socket' 4188 | 4189 | u1 = UDPSocket.new 4190 | u1.bind('127.0.0.1', 4913) 4191 | u2 = UDPSocket.new 4192 | u2.connect('127.0.0.1', 4913) 4193 | # Won't send a message to the receiver obj. 4194 | # Instead it will send a message via UDP socket. 4195 | u2.send :sleep, 0 4196 | # Will actually send a message to the receiver obj. 4197 | u2.__send__ ... 4198 | ``` 4199 | 4200 | ## Misc 4201 | 4202 | * 4203 | Write `ruby -w` safe code. 4204 | [[link](#always-warn)] 4205 | 4206 | * 4207 | Avoid hashes as optional parameters. Does the method do too much? (Object 4208 | initializers are exceptions for this rule). 4209 | [[link](#no-optional-hash-params)] 4210 | 4211 | * 4212 | Avoid methods longer than 10 LOC (lines of code). Ideally, most methods will 4213 | be shorter than 5 LOC. Empty lines do not contribute to the relevant LOC. 4214 | [[link](#short-methods)] 4215 | 4216 | * 4217 | Avoid parameter lists longer than three or four parameters. 4218 | [[link](#too-many-params)] 4219 | 4220 | * 4221 | If you really need "global" methods, add them to Kernel and make them 4222 | private. 4223 | [[link](#private-global-methods)] 4224 | 4225 | * 4226 | Use module instance variables instead of global variables. 4227 | [[link](#instance-vars)] 4228 | 4229 | ```Ruby 4230 | # bad 4231 | $foo_bar = 1 4232 | 4233 | # good 4234 | module Foo 4235 | class << self 4236 | attr_accessor :bar 4237 | end 4238 | end 4239 | 4240 | Foo.bar = 1 4241 | ``` 4242 | 4243 | * 4244 | Use `OptionParser` for parsing complex command line options and `ruby -s` 4245 | for trivial command line options. 4246 | [[link](#optionparser)] 4247 | 4248 | * 4249 | Code in a functional way, avoiding mutation when that makes sense. 4250 | [[link](#functional-code)] 4251 | 4252 | * 4253 | Do not mutate parameters unless that is the purpose of the method. 4254 | [[link](#no-param-mutations)] 4255 | 4256 | * 4257 | Avoid more than three levels of block nesting. 4258 | [[link](#three-is-the-number-thou-shalt-count)] 4259 | 4260 | * 4261 | Be consistent. In an ideal world, be consistent with these guidelines. 4262 | [[link](#be-consistent)] 4263 | 4264 | * 4265 | Use common sense. 4266 | [[link](#common-sense)] 4267 | 4268 | ## Tools 4269 | 4270 | Here are some tools to help you automatically check Ruby code against 4271 | this guide. 4272 | 4273 | ### RuboCop 4274 | 4275 | [RuboCop][] is a Ruby code style 4276 | checker based on this style guide. RuboCop already covers a 4277 | significant portion of the Guide, supports both MRI 1.9 and MRI 2.0 4278 | and has good Emacs integration. 4279 | 4280 | ### RubyMine 4281 | 4282 | [RubyMine](http://www.jetbrains.com/ruby/)'s code inspections are 4283 | [partially based](http://confluence.jetbrains.com/display/RUBYDEV/RubyMine+Inspections) 4284 | on this guide. 4285 | 4286 | # Contributing 4287 | 4288 | The guide is still a work in progress—some rules are lacking examples, 4289 | some rules don't have examples that illustrate them clearly enough. Improving 4290 | such rules is a great (and simple way) to help the Ruby community! 4291 | 4292 | In due time these issues will (hopefully) be addressed—just keep them in 4293 | mind for now. 4294 | 4295 | Nothing written in this guide is set in stone. It's my desire to work 4296 | together with everyone interested in Ruby coding style, so that we could 4297 | ultimately create a resource that will be beneficial to the entire Ruby 4298 | community. 4299 | 4300 | Feel free to open tickets or send pull requests with improvements. Thanks in 4301 | advance for your help! 4302 | 4303 | You can also support the project (and RuboCop) with financial 4304 | contributions via [Gratipay](https://gratipay.com/~bbatsov/). 4305 | 4306 | [![Support via Gratipay](https://cdn.rawgit.com/gratipay/gratipay-badge/2.3.0/dist/gratipay.png)](https://gratipay.com/~bbatsov/) 4307 | 4308 | ## How to Contribute? 4309 | 4310 | It's easy, just follow the [contribution guidelines](https://github.com/bbatsov/ruby-style-guide/blob/master/CONTRIBUTING.md). 4311 | 4312 | # License 4313 | 4314 | ![Creative Commons License](http://i.creativecommons.org/l/by/3.0/88x31.png) 4315 | This work is licensed under a [Creative Commons Attribution 3.0 Unported License](http://creativecommons.org/licenses/by/3.0/deed.en_US) 4316 | 4317 | # Spread the Word 4318 | 4319 | A community-driven style guide is of little use to a community that 4320 | doesn't know about its existence. Tweet about the guide, share it with 4321 | your friends and colleagues. Every comment, suggestion or opinion we 4322 | get makes the guide just a little bit better. And we want to have the 4323 | best possible guide, don't we? 4324 | 4325 | Cheers,
4326 | [Bozhidar](https://twitter.com/bbatsov) 4327 | 4328 | [PEP-8]: https://www.python.org/dev/peps/pep-0008/ 4329 | [rails-style-guide]: https://github.com/bbatsov/rails-style-guide 4330 | [pickaxe]: https://pragprog.com/book/ruby4/programming-ruby-1-9-2-0 4331 | [trpl]: http://www.amazon.com/Ruby-Programming-Language-David-Flanagan/dp/0596516177 4332 | [Pandoc]: http://pandoc.org/ 4333 | [RuboCop]: https://github.com/bbatsov/rubocop 4334 | [rdoc]: http://rdoc.sourceforge.net/doc/ 4335 | --------------------------------------------------------------------------------