Ruby Style Guide

469 views
294 views

Published on

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
469
On SlideShare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
3
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Ruby Style Guide

  1. 1. # ruby style# how to concision
  2. 2. # namingconventions!
  3. 3. # CamelCase for module and class names#OneModuleOneClass
  4. 4. # snake_case for variables, methods, andsymbols#one_variableis_a_method?now_a_method!:a_symbol
  5. 5. # CONSTANTS are variables that dont vary for# the duration of a program, they should be written# in SCREAMING_SNAKE_CASE#LOUD_AND_PROUD_CONSTANT = "globalaccess"# class and module names in ruby are constants# we write their names in camel case by convention#class CamelCase
  6. 6. # avoid single letter variables except for# when their use is very clear#num = (1..100).reverse_each {|x| puts x }
  7. 7. # an exclamation mark is used by convention# for methods that change the state of the# object they are called on.# these are called dangerous methods#strings.mutate_in_ruby! # good to know
  8. 8. # a question mark is used by convention# for methods that return true or false,# these are called predicate methods#assertion.is_naming_convention? # true
  9. 9. # an equals sign is used at the end of# method names that make assignments# these are called setter methods’# and is SYNTACTIC#class SomeClassdef setter=( value )@instance_variable = valueendend
  10. 10. # setter methods can be called with# simplified syntax (syntactic sugar)#instance = SomeClass.newinstance.setter=(new_value) # can doinstance.setter = new_value # should do# there’s a lot of this in Rails
  11. 11. # a common mistake is trying to use# it inside class definitions without# specifying the object#class SomeClassdef setter=( value )@instance_variable = valueendinstance_variable = value # doesn’t work andinstance_variable=(value) # is trying to do thisself.instance_variable = value # do thisend
  12. 12. # with setters inside a class, just rememberthat:#<<RULEAssignment expressions will only invoke asetter method when invoked through anobject.RULE
  13. 13. ruby.can_use_semicolons? # true# but please dont unless you really# want more than one statement per line#can_be tidy; can_also_be obfuscated;
  14. 14. # whitespace# indent with 2 spaces# dont use tabs... ever# always put whitespace around the# assignment operator#foo = 1
  15. 15. # unless youre setting default# method parameters#def foo( baz=2 )puts 2 ** bazend
  16. 16. # use underscores to make long# numbers more readable#10000000000 # how many zeros?10_000_000_000 # keeps fingers off the screen
  17. 17. DoNot::call::methods::with_double_colons# yes, you can do it#a = 256::to_s::reverse!::to_i * 2 # 1304# but it’s usually thought of as constant access#SomeObject::ITS_CONSTANT
  18. 18. # when block commenting it is nice to# leave a blank line before the actual# code for the sake of readability#def apprehend( archibald )archibald.get_himend
  19. 19. "Strings"
  20. 20. # for strings with lots of odd characters# it can be better to use the alternative# string literal syntax to avoid using escapes#string = %q[<a href="javascript:method(call)">js?</a>]# resolves to "<ahref="javascript:method(call)">js?</a>"
  21. 21. # if you have a really big string it# can be better to define it like so#big_string = <<delimiter]})@#$^UHEOIG(FKALSNCthis is just one stringand that is totally okay()@))_-p[[}{P{{p[]}{[delimiter
  22. 22. # this is arguably inferior:#big_string = "this string right here " +" be concatenated with this one" +" aaaaand this one too" +" all these concatenations" +" are all a bit tiresome, no?"
  23. 23. # << or <<- can also be useful for# passing big strings as arguments#DoesTheObjectMatter.new(:value => <<-eosdont worry about this its alljust one big string, no one isthe wisereosthis = :no_longer_the_above_string
  24. 24. # passing arguments with hash-like syntax# can save other peoples time when reading# your code:#divide(1, 3) # which is which?divide(:num => 1, :denom => 3) # clearer
  25. 25. # you can designate code blocks two ways.# the conventional way for multi-liners is with#do...end
  26. 26. # you can also use { .. } but please# only use those for single-line blocks#single_line_block = (1..1000).map {|x| x**2 }
  27. 27. # procs and lambdas can be helpful for keeping# your code DRY, among myriad other things.# use the lambda literal syntax (not keyword)# for good style#anonymous_method = ->( p_one, p_two ) dop_one + " and " + p_twoend
  28. 28. # boolean logic!
  29. 29. and, or != &&, ||
  30. 30. # use &&, ||
  31. 31. # and, or are seldom used by convention# and can do unexpected things because they# bind differently than &&, ||#puts nil || "rainier" # this prints "rainier"puts nil or "rainier" # this prints nil
  32. 32. # why? the later parses to:#puts (nil) or "rainier"# the former to:#puts ( nil || "rainier" )
  33. 33. # one-line if statements# works#variable = if test then pos_result else neg_resultend# better#variable = test ? pos_result : neg_result
  34. 34. # nest if like this:#if testnest_test ? nest_result : nest_other_resultelsefirst_layer_resultend# deeply nested if statements are generally# considered to be bad style
  35. 35. # use unless instead of negative if#something.action if !test # questionablesomething.action unless test # better# but never use unless with else# use an if instead.
  36. 36. # but never use unlesswith else# use an if instead# similar situation with while/until#something.action while !test # nosomething.action until test # yes
  37. 37. # use ||= to freely initialize variables# to avoid unnecessary if statements#variable ||= kenny wheeler
  38. 38. # if the first argument begins with a parentheses# then use parentheses in method invocation# this is a common source of consternation.#method ( 3 + 2 ) % 2 # ambiguousmethod(( 3 + 2 ) % 2) # unambiguous(method( 3 + 2 ) % 2) # unambiguous
  39. 39. gem install rubocop<<-arbitrary_string_delimiterfrom the README:rubocop is a Ruby code style checker based on theRuby Style Guide, which is available on github:https://github.com/bbatsov/ruby-style-guiderubocop is pretty strict, but can be usefularbitrary_string_delimiter

×