SlideShare a Scribd company logo
1 of 39
# ruby style
# how to concision
# naming
conventions!
# CamelCase for module and class names
#
OneModule
OneClass
# snake_case for variables, methods, and
symbols
#
one_variable
is_a_method?
now_a_method!
:a_symbol
# CONSTANTS are variables that don't vary for
# the duration of a program, they should be written
# in SCREAMING_SNAKE_CASE
#
LOUD_AND_PROUD_CONSTANT = "global
access"
# class and module names in ruby are constants
# we write their names in camel case by convention
#
class CamelCase
# avoid single letter variables except for
# when their use is very clear
#
num = (1..100).reverse_each {|x| puts x }
# 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
# a question mark is used by convention
# for methods that return true or false,
# these are called 'predicate methods'
#
assertion.is_naming_convention? # true
# an equals sign is used at the end of
# method names that make assignments
# these are called 'setter methods’
# and is SYNTACTIC
#
class SomeClass
def setter=( value )
@instance_variable = value
end
end
# setter methods can be called with
# simplified syntax (syntactic sugar)
#
instance = SomeClass.new
instance.setter=(new_value) # can do
instance.setter = new_value # should do
# there’s a lot of this in Rails
# a common mistake is trying to use
# it inside class definitions without
# specifying the object
#
class SomeClass
def setter=( value )
@instance_variable = value
end
instance_variable = value # doesn’t work and
instance_variable=(value) # is trying to do this
self.instance_variable = value # do this
end
# with setters inside a class, just remember
that:
#
<<RULE
Assignment expressions will only invoke a
setter method when invoked through an
object.
RULE
ruby.can_use_semicolons? # true
# but please don't unless you really
# want more than one statement per line
#
can_be tidy; can_also_be obfuscated;
# whitespace
# indent with 2 spaces
# don't use tabs... ever
# always put whitespace around the
# assignment operator
#
foo = 1
# unless you're setting default
# method parameters
#
def foo( baz=2 )
puts 2 ** baz
end
# use underscores to make long
# numbers more readable
#
10000000000 # how many zeros?
10_000_000_000 # keeps fingers off the screen
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
# 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_him
end
"Strings"
# 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 "<a
href="javascript:method('call')">js?</a>"
# if you have a really big string it
# can be better to define it like so
#
big_string = <<delimiter
]})@#$^UHEOIG(FKALSNC
this is just one string
and that is totally okay
()@))_-p[[}{P{{p[]}{[
delimiter
# 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?"
# << or <<- can also be useful for
# passing big strings as arguments
#
DoesTheObjectMatter.new(:value => <<-eos
don't worry about this it's all
just one big string, no one is
the wiser
eos
this = :no_longer_the_above_string
# passing arguments with hash-like syntax
# can save other people's time when reading
# your code:
#
divide(1, 3) # which is which?
divide(:num => 1, :denom => 3) # clearer
# you can designate code blocks two ways.
# the conventional way for multi-liners is with
#
do
...
end
# you can also use '{ .. }' but please
# only use those for single-line blocks
#
single_line_block = (1..1000).map {|x| x**2 }
# 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 ) do
p_one + " and " + p_two
end
# boolean logic!
and, or != &&, ||
# use &&, ||
# '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
# why? the later parses to:
#
puts (nil) or "rainier"
# the former to:
#
puts ( nil || "rainier" )
# one-line 'if' statements
# works
#
variable = if test then pos_result else neg_result
end
# better
#
variable = test ? pos_result : neg_result
# nest 'if' like this:
#
if test
nest_test ? nest_result : nest_other_result
else
first_layer_result
end
# deeply nested 'if' statements are generally
# considered to be bad style
# use 'unless' instead of negative 'if'
#
something.action if !test # questionable
something.action unless test # better
# but never use 'unless' with 'else'
# use an 'if' instead.
# but never use 'unless'
with 'else'
# use an 'if' instead
# similar situation with while/until
#
something.action while !test # no
something.action until test # yes
# use ||= to freely initialize variables
# to avoid unnecessary 'if' statements
#
variable ||= 'kenny wheeler'
# 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 # ambiguous
method(( 3 + 2 ) % 2) # unambiguous
(method( 3 + 2 ) % 2) # unambiguous
gem install rubocop
<<-arbitrary_string_delimiter
from the README:
rubocop is a Ruby code style checker based on the
Ruby Style Guide, which is available on github:
https://github.com/bbatsov/ruby-style-guide
rubocop is pretty strict, but can be useful
arbitrary_string_delimiter

More Related Content

Similar to Ruby Style Guide

Similar to Ruby Style Guide (20)

Ruby from zero to hero
Ruby from zero to heroRuby from zero to hero
Ruby from zero to hero
 
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)
 
python.pdf
python.pdfpython.pdf
python.pdf
 
Ruby Intro {spection}
Ruby Intro {spection}Ruby Intro {spection}
Ruby Intro {spection}
 
Learning Ruby
Learning RubyLearning Ruby
Learning Ruby
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objects
 
Eloquent ruby
Eloquent rubyEloquent ruby
Eloquent ruby
 
Write your Ruby in Style
Write your Ruby in StyleWrite your Ruby in Style
Write your Ruby in Style
 
Clean code
Clean codeClean code
Clean code
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
 
Ruby Programming
Ruby ProgrammingRuby Programming
Ruby Programming
 
Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technology
 
Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介
 
No comment
No commentNo comment
No comment
 
Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introduction
 
Ruby
RubyRuby
Ruby
 

Recently uploaded

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 

Recently uploaded (20)

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 

Ruby Style Guide

  • 1. # ruby style # how to concision
  • 3. # CamelCase for module and class names # OneModule OneClass
  • 4. # snake_case for variables, methods, and symbols # one_variable is_a_method? now_a_method! :a_symbol
  • 5. # CONSTANTS are variables that don't vary for # the duration of a program, they should be written # in SCREAMING_SNAKE_CASE # LOUD_AND_PROUD_CONSTANT = "global access" # class and module names in ruby are constants # we write their names in camel case by convention # class CamelCase
  • 6. # avoid single letter variables except for # when their use is very clear # num = (1..100).reverse_each {|x| puts x }
  • 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. # 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. # an equals sign is used at the end of # method names that make assignments # these are called 'setter methods’ # and is SYNTACTIC # class SomeClass def setter=( value ) @instance_variable = value end end
  • 10. # setter methods can be called with # simplified syntax (syntactic sugar) # instance = SomeClass.new instance.setter=(new_value) # can do instance.setter = new_value # should do # there’s a lot of this in Rails
  • 11. # a common mistake is trying to use # it inside class definitions without # specifying the object # class SomeClass def setter=( value ) @instance_variable = value end instance_variable = value # doesn’t work and instance_variable=(value) # is trying to do this self.instance_variable = value # do this end
  • 12. # with setters inside a class, just remember that: # <<RULE Assignment expressions will only invoke a setter method when invoked through an object. RULE
  • 13. ruby.can_use_semicolons? # true # but please don't unless you really # want more than one statement per line # can_be tidy; can_also_be obfuscated;
  • 14. # whitespace # indent with 2 spaces # don't use tabs... ever # always put whitespace around the # assignment operator # foo = 1
  • 15. # unless you're setting default # method parameters # def foo( baz=2 ) puts 2 ** baz end
  • 16. # use underscores to make long # numbers more readable # 10000000000 # how many zeros? 10_000_000_000 # keeps fingers off the screen
  • 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. # 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_him end
  • 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 "<a href="javascript:method('call')">js?</a>"
  • 21. # if you have a really big string it # can be better to define it like so # big_string = <<delimiter ]})@#$^UHEOIG(FKALSNC this is just one string and that is totally okay ()@))_-p[[}{P{{p[]}{[ delimiter
  • 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. # << or <<- can also be useful for # passing big strings as arguments # DoesTheObjectMatter.new(:value => <<-eos don't worry about this it's all just one big string, no one is the wiser eos this = :no_longer_the_above_string
  • 24. # passing arguments with hash-like syntax # can save other people's time when reading # your code: # divide(1, 3) # which is which? divide(:num => 1, :denom => 3) # clearer
  • 25. # you can designate code blocks two ways. # the conventional way for multi-liners is with # do ... end
  • 26. # you can also use '{ .. }' but please # only use those for single-line blocks # single_line_block = (1..1000).map {|x| x**2 }
  • 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 ) do p_one + " and " + p_two end
  • 29. and, or != &&, ||
  • 30. # use &&, ||
  • 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. # why? the later parses to: # puts (nil) or "rainier" # the former to: # puts ( nil || "rainier" )
  • 33. # one-line 'if' statements # works # variable = if test then pos_result else neg_result end # better # variable = test ? pos_result : neg_result
  • 34. # nest 'if' like this: # if test nest_test ? nest_result : nest_other_result else first_layer_result end # deeply nested 'if' statements are generally # considered to be bad style
  • 35. # use 'unless' instead of negative 'if' # something.action if !test # questionable something.action unless test # better # but never use 'unless' with 'else' # use an 'if' instead.
  • 36. # but never use 'unless' with 'else' # use an 'if' instead # similar situation with while/until # something.action while !test # no something.action until test # yes
  • 37. # use ||= to freely initialize variables # to avoid unnecessary 'if' statements # variable ||= 'kenny wheeler'
  • 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 # ambiguous method(( 3 + 2 ) % 2) # unambiguous (method( 3 + 2 ) % 2) # unambiguous
  • 39. gem install rubocop <<-arbitrary_string_delimiter from the README: rubocop is a Ruby code style checker based on the Ruby Style Guide, which is available on github: https://github.com/bbatsov/ruby-style-guide rubocop is pretty strict, but can be useful arbitrary_string_delimiter