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

The Elements of Style in Ruby (RubyConf.by)

The Elements of Style in Ruby (RubyConf.by)

Slide deck from my talk at RubyConf.by 2015

Efd2550fb5f3059d815e731ecd61b701?s=128

Bozhidar Batsov

March 28, 2015
Tweet

Transcript

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

  2. Прывітанне!

  3. None
  4. None
  5. None
  6. None
  7. None
  8. None
  9. VP of Engineering

  10. None
  11. (think) http://batsov.com

  12. Emacs Redux http://emacsredux.com

  13. @bbatsov

  14. bbatsov

  15. None
  16. None
  17. None
  18. None
  19. None
  20. None
  21. github.com/ bbatsov

  22. I’m a perfectionist

  23. 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
  24. Languages are complex

  25. None
  26. Basic use of a language is relatively easy

  27. None
  28. Ain-tsu-tsvai-tsu-drun

  29. “Two parts, sometimes lyun, sometimes win, so, first day relyax"

  30. Correct use of a language is hard

  31. Effective use of a language is very hard

  32. None
  33. None
  34. Use the active voice.

  35. My first visit to Minsk will always be remembered by

    me. lame
  36. I shall always remember my first visit to Minsk. legit

  37. The word personally is often unnecessary.

  38. Personally, I love Ruby.

  39. 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
  40. Convention over configuration

  41. Style guides are not substitutes for common sense

  42. Common sense is not so common…

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

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

  45. None
  46. English

  47. 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
  48. 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
  49. Русский

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

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

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

  53. def some_method do_something do_more do_more end

  54. def some_method do_something do_more do_more end

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

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

  57. English

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

  59. Bozhidar’s talk Batman’s batclaw Emacs’s magic

  60. Ruby

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

  62. even? completed? batman?

  63. English

  64. Make the paragraph the unit of composition.

  65. Ruby

  66. Make the method the unit of composition.

  67. English

  68. Omit needless words.

  69. he is a man who

  70. Her story is a strange one.

  71. Ruby

  72. Omit needless words.

  73. if some_condition then # body omitted end

  74. def some_method # ... return result end

  75. English

  76. farther further

  77. Do we have to go much farther?

  78. I decided to pursue the subject further.

  79. Ruby

  80. == === equal? eql?

  81. 5 === Fixnum Fixnum === 5

  82. An Approach To Style

  83. Be consistent.

  84. Be clear.

  85. English

  86. CPU

  87. COTFLGOHAHA

  88. Crawling on the Floor Laughing Guts Out and Having a

    Heart Attack
  89. Русский

  90. КПД

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

  92. НИИИАТ

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

  94. Ruby

  95. $:

  96. $LOAD_PATH

  97. $;

  98. $FIELD_SEPARATOR

  99. $*

  100. $ARGV

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

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

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

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

  105. Ruby is optimised for programmer happiness.

  106. Ruby is a huge language

  107. Making the “right” choices is hard

  108. puts "Hello, Minsk!" puts "Hello, Minsk!" puts "Hello, Minsk!"

  109. for i in 1..3 puts "Hello, Minsk!" end

  110. 3.times do puts "Hello, Minsk!" end

  111. 3.times { puts "Hello, Minsk!" }

  112. 3.times do puts 'Hello, Minsk!' end

  113. Fuck this shit!!!

  114. result = [] for name in names result << name.upcase

    end
  115. result = [] names.each do |name| result << name.upcase end

  116. names.collect { |name| name.upcase }

  117. names.collect(&:upcase)

  118. names.map(&:upcase)

  119. Fuck this shit!!!

  120. None
  121. None
  122. None
  123. 56 simple rules

  124. Format a program to help the reader understand it.

  125. Write clearly -- don't be too clever.

  126. def user_signed_in? !!@current_user end def user_signed_in? !@current_user.nil? end

  127. Don't sacrifice clarity for small gains in efficiency.

  128. i = 1 res = 0 while i <= 10

    res += i i += 1 end
  129. (1..10).reduce(:+)

  130. (N * (N + 1)) / 2

  131. (10 * (10 + 1)) / 2

  132. Don't diddle code to make it faster -- find a

    better algorithm.
  133. • Make it right before you make it faster. •

    Make it fail-safe before you make it faster. • Make it clear before you make it faster.
  134. Instrument your programs. Measure before making efficiency changes.

  135. Use variable names that mean something.

  136. a s l

  137. age sex location

  138. age_over_18?

  139. adult?

  140. Don’t repeat yourself

  141. Parenthesize to avoid ambiguity.

  142. x || y && z

  143. x || (y && z)

  144. Keep the code & its comments in sync

  145. # This method does bla bla bla. # It returns

    an array of results. def bla_bla_bla res = Set.new # ... res end
  146. bla_bla_bla[0] # => Boom Boom Pow bla_bla_bla.uniq # => Kaboom!

  147. //private instance variable for storing age public static int age;

  148. //private instance variable for storing age public static int age;

  149. //private instance variable for storing age public static int age;

  150. Fuck this shit!!!

  151. The Community Ruby Style Guide

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

  153. Built on solid foundation

  154. None
  155. With the help of a legion of Ruby hackers

  156. With a focus on

  157. Simplicity

  158. Clarity

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

    code • Linkable • Neatly organised • Community-approved
  160. 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
  161. More than 200 rules!

  162. Style evolution

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

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

  165. object. one. two. three. four

  166. object .one .two .three .four

  167. private def m1 end def m2 end

  168. def m1 end def m2 end private :m1, :m2

  169. private def m1 end private def m2 end

  170. None
  171. International • Chinese Simplified • Chinese Traditional • French •

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

  173. GitHub Ruby Style Guide

  174. Inspiration for other style guides

  175. The Elements of Ruby Style ? ?

  176. Style consistency

  177. Community PersonalProject Company

  178. Community Project Company

  179. None
  180. 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
  181. None
  182. None
  183. Auto-correct

  184. 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
  185. Highly customisable

  186. You ain’t nothing if you ain’t got style.

  187. Дзякуй