Save 37% off PRO during our Black Friday Sale! »

The Elements of Style in Ruby

Efd2550fb5f3059d815e731ecd61b701?s=47 Bozhidar Batsov
September 30, 2014
70

The Elements of Style in Ruby

Slides from my talk at RailsClub.ru 2014

Efd2550fb5f3059d815e731ecd61b701?s=128

Bozhidar Batsov

September 30, 2014
Tweet

Transcript

  1. The Elements of Style in Ruby by Bozhidar I. Batsov

  2. Привет!

  3. None
  4. None
  5. None
  6. None
  7. @bbatsov

  8. None
  9. None
  10. github.com/bbatsov

  11. github.com/bbatsov

  12. I’m a perfectionist

  13. size=2 start=0 c=['Н', 'Н' ,'Н' ,'Н' ,'Н','Н','Н','Н','Н','Н','Н','Н','Н','Н'] code_dictionary=Array.new() begin_size_code_dictionary=Array.new() end_string=String.new()

    code_dictionary=c.uniq.to_a decode_dictionary=c.uniq.to_a for i in 0...code_dictionary.size begin_size_code_dictionary[i]=i end c.size.times{ if !code_dictionary.include?(c[start,size].to_s)#Comparation code_dictionary.push(c[start,size].to_s.chomp) start=start+(code_dictionary.last.size)/2-1 size=2 else size+=1; end } end_code=Array.new(code_dictionary.size) for i in begin_size_code_dictionary.size...code_dictionary.size end_code[i]=code_dictionary.index(code_dictionary[i].chop.chop)+1 end_string+=code_dictionary[i].chop.chop end govnokod.ru
  14. Languages are complex

  15. None
  16. Basic use of a language is relatively easy

  17. Correct use of a language is hard

  18. Effective use of a language is very hard

  19. None
  20. None
  21. Use the active voice.

  22. My first visit to Moscow will always be remembered by

    me. lame
  23. I shall always remember my first visit to Moscow. legit

  24. The word personally is often unnecessary.

  25. Personally, I love Ruby.

  26. Style guide • curated set of (supposedly) good practices •

    frees you from making trivial decisions • allows you to focus on the real problems • short and to the point
  27. Convention over configuration

  28. Style guides are not substitutes for common sense

  29. Common sense is not so common…

  30. Programs must be written for people to read, and only

    incidentally for machines to execute. ! — Hal Abelson
  31. Similar rules apply for natural and programming languages

  32. None
  33. English

  34. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do

    eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Chapter I
  35. LOREM IPSUM DOLOR SIT AMET, CONSECTETUR ADIPISCING ELIT, SED DO

    EIUSMOD TEMPOR INCIDIDUNT UT LABORE ET DOLORE MAGNA ALIQUA. UT ENIM AD MINIM VENIAM, QUIS NOSTRUD EXERCITATION ULLAMCO LABORIS NISI UT ALIQUIP EX EA COMMODO CONSEQUAT. DUIS AUTE IRURE DOLOR IN REPREHENDERIT IN VOLUPTATE VELIT ESSE CILLUM DOLORE EU FUGIAT NULLA PARIATUR. EXCEPTEUR SINT OCCAECAT CUPIDATAT NON PROIDENT, SUNT IN CULPA QUI OFFICIA DESERUNT MOLLIT ANIM ID EST LABORUM. LOREM IPSUM DOLOR SIT AMET, CONSECTETUR ADIPISCING ELIT, SED DO EIUSMOD TEMPOR INCIDIDUNT UT LABORE ET DOLORE MAGNA ALIQUA. UT ENIM AD MINIM VENIAM, QUIS NOSTRUD EXERCITATION ULLAMCO LABORIS NISI UT ALIQUIP EX EA COMMODO CONSEQUAT. DUIS AUTE IRURE DOLOR IN REPREHENDERIT IN VOLUPTATE VELIT ESSE CILLUM DOLORE EU FUGIAT NULLA PARIATUR. EXCEPTEUR SINT OCCAECAT CUPIDATAT NON PROIDENT, SUNT IN CULPA QUI OFFICIA DESERUNT MOLLIT ANIM ID EST LABORUM. chapter i
  36. Русский

  37. Эи дуо модо лудуз кэтэро, ты фачтидёе зючкёпит эффикеэнди эжт.

    Нэ путынт дикырыт кюм. Коммюны пожйдонёюм экз ыюм, омныз мыдиокрым хонэзтатёз вяш йн. Эож ед чент граэкы праэчынт. Эож золэт зэнтынтиаэ рыпримёквуы ат. Дёжкэрэ эрепюят ыам ты, квуым ныморэ глориатюр кюм ед, эа прё долорэж аккюмзан интылльэгэбат. ! Мыа йн граэкйж волютпат интыллыгам. Нам ёудёкабет рыпримёквуы ты, ад прё вёжи экшырки доминг. Дикырыт адипижкй эффякиантур хёз эа. Но кюм жанктюч торквюатоз, эрож рыкючабо мыа нэ, ат вим кибо зкрипторэм. Еллум граэкы рыпудяары ед мыа. Глава 1
  38. ЭИ ДУО МОДО ЛУДУЗ КЭТЭРО, ТЫ ФАЧТИДЁЕ ЗЮЧКЁПИТ ЭФФИКЕЭНДИ ЭЖТ.

    НЭ ПУТЫНТ ДИКЫРЫТ КЮМ. КОММЮНЫ ПОЖЙДОНЁЮМ ЭКЗ ЫЮМ, ОМНЫЗ МЫДИОКРЫМ ХОНЭЗТАТЁЗ ВЯШ ЙН. ЭОЖ ЕД ЧЕНТ ГРАЭКЫ ПРАЭЧЫНТ. ЭОЖ ЗОЛЭТ ЗЭНТЫНТИАЭ РЫПРИМЁКВУЫ АТ. ДЁЖКЭРЭ ЭРЕПЮЯТ ЫАМ ТЫ, КВУЫМ НЫМОРЭ ГЛОРИАТЮР КЮМ ЕД, ЭА ПРЁ ДОЛОРЭЖ АККЮМЗАН ИНТЫЛЛЬЭГЭБАТ. гЛаВа 1 МЫА ЙН ГРАЭКЙЖ ВОЛЮТПАТ ИНТЫЛЛЫГАМ. НАМ ЁУДЁКАБЕТ РЫПРИМЁКВУЫ ТЫ, АД ПРЁ ВЁЖИ ЭКШЫРКИ ДОМИНГ. ДИКЫРЫТ АДИПИЖКЙ ЭФФЯКИАНТУР ХЁЗ ЭА. НО КЮМ ЖАНКТЮЧ ТОРКВЮАТОЗ, ЭРОЖ РЫКЮЧАБО МЫА НЭ, АТ ВИМ КИБО ЗКРИПТОРЭМ. ЕЛЛУМ ГРАЭКЫ РЫПУДЯАРЫ ЕД МЫА.
  39. Ruby

  40. def some_method do_something do_more do_more end

  41. def some_method do_something do_more do_more end

  42. sum = 1 + 2 a, b = 1, 2

    [1, 2, 3].each { |e| puts e } class FooError < StandardError; end
  43. sum=1+2 a,b=1,2 [1,2,3].each{|e|puts e} class FooError<StandardError;end

  44. English

  45. Form possessive singular of nouns by adding ’s.

  46. Bozhidar’s talk ! Batman’s batclaw ! Emacs’s magic

  47. Ruby

  48. Form predicate method names by adding “?”.

  49. even? ! completed? ! batman?

  50. English

  51. Make the paragraph the unit of composition.

  52. Ruby

  53. Make the method the unit of composition.

  54. English

  55. Omit needless words.

  56. he is a man who

  57. Her story is a strange one.

  58. Ruby

  59. Omit needless words.

  60. if some_condition then # body omitted end

  61. def some_method # ... ! return result end

  62. English

  63. farther ! further

  64. Do we have to go much farther?

  65. I decided to pursue the subject further.

  66. Ruby

  67. == === equal? eql?

  68. 5 === Fixnum ! Fixnum === 5

  69. An Approach To Style

  70. Be consistent.

  71. Be clear.

  72. Русский

  73. КПД

  74. Коэффициент полезного действия

  75. НИИИАТ

  76. Научно-исследовательский испытательный институт автомобильной техники

  77. Ruby

  78. $:

  79. $LOAD_PATH

  80. $;

  81. $FIELD_SEPARATOR

  82. $*

  83. $ARGV

  84. '%d %d' % [20, 10]

  85. sprintf('%d %d', 20, 10)

  86. sprintf( '%{first} %{second}', first: 20, second: 10 )

  87. format('%{first} %{second}', first: 20, second: 10)

  88. Ruby is optimised for programmer happiness.

  89. Ruby is a huge language

  90. Making the “right” choices is hard

  91. for i in 1..3 puts "Hello, Moscow!" end

  92. 3.times do puts "Hello, Moscow!" end

  93. result = [] ! names.each do |word| result << name.upcase

    end
  94. names.map { |name| name.upcase }

  95. names.map(&:upcase)

  96. None
  97. The Community Ruby Style Guide

  98. A short time ago in an office far, far away…

  99. Built on solid foundation

  100. None
  101. With the help of a legion of Ruby hackers

  102. With a focus on

  103. Simplicity

  104. Simplicity is the ultimate sophistication.

  105. Clarity

  106. The Rules • Clear and concise • Illustrated with example

    code • Linkable • Neatly organised • Community-approved
  107. More than 200 rules!

  108. Style evolution

  109. { :batman => 'Bruce', :superman => 'Clark', :zorro => 'Diego',

    :catwoman => 'Selina' }
  110. { batman: 'Bruce', superman: 'Clark', zorro: 'Diego', catwoman: 'Selina' }

  111. object. one. two. three. four

  112. object .one .two .three .four

  113. Bikeshedding

  114. Style rules that only reflect what is easily discoverable by

    a trivial examination of the source code seem to me to be the least valuable rules. If the style is not conveying additional information, why bother? ! — Jim Weirich
  115. None
  116. International • Chinese Simplified • Chinese Traditional • French •

    Japanese • Portuguese • Russian • Spanish • Vietnamese • Korean
  117. Rails Style Guide

  118. GitHub Ruby Style Guide

  119. Inspiration for other style guides

  120. The Elements of Ruby Style ? ?

  121. None
  122. def some_method begin x = 5 ! h={:a=>1,:b=>2} if not

    h raise "Some error occurred" end ! [1, 2, 3].select { |e| e.even? } rescue => e end end
  123. None
  124. None
  125. Auto-correct

  126. def some_method x = 5 ! h = { a:

    1, b: 2 } unless h fail 'Some error occurred' end ! [1, 2, 3].select(&:even?) rescue => e end
  127. Highly customisable

  128. Конец