SlideShare a Scribd company logo
RubyCodingConvention
(DRAFT VERSION: 2001/11/01)


File Names

Directory and File names and Suffixes

Ruby source code
file/directory name is lower case class/module name with suffix '.rb'.

ex.
      Foo class => foo.rb
      Bar module => bar.rb
      FooBar class => foobar.rb (Normal Rule)
                      foo_bar.rb (Rails Rule)
      Foo::Bar class => foo/bar.rb
            *1
Libraries
non-standard multiple files required by a script should be in one directory, and they should
be installed to the standard site-ruby directory or a script's library directory.
don't use a current directory for libraries --- it is dangerous. since the directory in which
script exists can not be specified portably, it is also not suited for libraries.


File Organization
       •   require (if necessary)
       •   include (if necessary)
       •   classes and modules definition
       •   main
       •   testing code(?) using __FILE__ idiom

           ex:
             if __FILE__ == $0
               <testcode>
             end

Beginning Comment

begin - end style

for file header or footer.

=begin
  * Name:
  * Description
  * Author:
  * Date:
* License:
=end

using '#' style

for class/module and method definitions

# using foo bar
#
# foo bar buz.
#
class Foo

  # bar.bar.bar.
  #
  class Bar

        # constructor of Bar.
        #
        def initialize(bar = nil)
          super(bar)
        end

        def bar
          self
        end

  end

  def initialize()
  end

end


Indentation

Line length

Max length is about 80 characters.

Wrapping Line

      • Break after comma
      • Break after operator


Comments
Ruby has two comments style: =begin...=end and '#'. You should use =begin...=end for
Documentation Comments, and '#' for both Documentation Comments and Implementation
Comments.
Implementation Comments

Block Comments

# Here is block comment.
#
# foo, bar, buz.

Single-Line Comments

# this is single line comment.

## this is also single line comment.

Tailing Comments

if a == 2
  true           # special case
else
  prime?(a)      # work only for odd a
end

Documentation Comments

Header/Footer

=begin

= FooBar library

== What's New?
.....
....

== Installation
.....
....

....

=end

In Class/Module

# .....
# ....
#
def foo()
  ..
or

##
# .....
# ....
#
def foo()
   ..

Way of no commenting

If you can write simple, short and light scripts, comments may not be necessary.
You can let the script itself tell everything, instead of embedding documentation that may
confuse readers of your script.


Definitions

Initialization

Ruby variables have no 'definitions'. So, you should initialize variables.

One initialization per line

level = 0
size = 0

is preferred over

level = size = 0

Placement

Statements

Simple Statements

Each line should contain at most one statement.

foo = 1    ## Correct
bar = 2    ## Correct

foo = 1; bar = 2      ## AVOID!

Compound Statements

if-end, if-else-end, if-elsif-else-end Statements

simple example:
if <condition>
    <statements>
  end

more complex example:

 if <condition>
   <statements>
 elsif <condition>
   <statements>
 else
   <statements>
 end

You can put on <condition> after <statements> when <statements> is one-line.

<statements> if <condition>

block methods

`{...}' style:

bar.foo(vars){|vars2|
  <statements>
}

`do...end' style:

bar.foo(vars) do |vars2|
  <statements>
end

one-line block:

bar.foo(){|var|     <statements> }

case-when Statements

Ruby's case-when (not when-case) does not need 'break'.

case foo
when condition1
  <statements>
when condition2
  <statements>
else
  <statements>
end

begin-rescue-end Statements

It handles errors (Exceptions).
begin
  <statements>
rescue FooError => e
  <statements>
rescue BazError => e2
  <statements>
rescue
  <statements>
end


White Space

Blank Lines

      •   Between sections of a source file
      •   Between class and module definitions
      •   Between methods
      •   Before blocks or single-line comments
      •   Between logical sections inside a method to improve readability

Blank spaces

A keyword followed by a parenthesis should be separated by a space.

ex:
  while (foo.end?) {
    <statements>
  }

The number of spaces should be balanced.

a+b         ##   Correct
a + b       ##   Correct
a+ b        ##   AVOID!
a +b        ##   AVOID! (Erroneous: interpreted as a(+b))

a += b + c
a = (a + b) / (c * d)
a = b
foo(quot;fooquot; + buz + bar)


Naming Conventions

Classes/Modules

class and module names should be nouns; in mixed case with the first letter of each internal
word capitalized.

ex:   class Raster,      class Raster::ImageSprite
Methods

Methods should be verbs. All lower case ASCII letters with words separated by underscores
('_')

ex.   run(), run_fast(), obj.background_color()

Variables

variable names should be all lower case ASCII letters with words separated by underscore
('_')

ex:
      i = 1
      some_char = SomeChar.new()
      table_width = 0.0

Constants
                                                                                *2
constants should be all upper case with words separated by underscores ('_').

ex:
      MIN_LENGTH = 1
      DEFAULT_HOST = quot;foo.example.comquot;

Omission

Speaking of 'Connection Pool' as a variable, you should decide to prefer name by scope such
as the following...
     • 'conpool' for local scope (such as local variable)
     • '@connection_pool' for class scope (such as instance variable)


Pragmatic Programming Practices

Using attr_* to access

def foo()
  @foo
end

attr_reader :foo

Without Parenthesis

Some methods are used without parenthesis.
    • require

        ex. require 'foo/bar'

      • include
ex. include FooModule

       • p

         ex. p foo

       • attr_*

         ex. attr_reader :foo, :bar

Reduce repetition

When successive lines of a script share something,

x = ModuleA::ClassB::method_c( a )
y = ModuleA::ClassB::method_d( b )

(-- 'function' => 'method' --)
you should make it like this:

cb = ModuleA::ClassB
x = cb::method_c( a )
y = cb::method_d( b )

You can also do:

include ModuleA
x = ClassB::method_c(a)
y = ClassB::method_d(b)


Code Example

Ruby Source File Example

=begin
  blahdy/blah.rb
  $Id:$

  Copyright (c) 2001 TAKAHASHI Masayoshi

  This is free software; you can copy and distribute and modify
  this program under the term of Ruby's License
  (http://www.ruby-lang.org/LINCENSE.txt)

=end

#
# module description goes here.
#
# @version: 1.82
# @author: TAKAHASHI Masayoshi
#
module Blahdy

     class Blah < SomeClass
       # A class implementation comment goes here.

       # CLASS_VAR1 documentation comment
       CLASS_VAR1 = 1;

       # CLASS_VAR2 documentation comment that happens
       # to be more than one line length.
       #
       CLASS_VAR2 = 1;

       # ...constructor Blah documentation comment...
       #
       def initialize()
         ## ...implementation goes here...
       end

       # ...method do_something documentation comment...
       #
       def do_sometiong()
         ## ...implementation goes here...
       end

       # ...method do_something_else documentation comment...
       #
       # @param some_param description
       #
       def do_something_else(some_param)
         ## ...implementation goes here...
       end

     end

end

*1
  any arguments?
*2
  Huh, is there a reasonable background to distinguish constants from a class name which is a constant at the
same time?

More Related Content

What's hot

Regular expressions
Regular expressionsRegular expressions
Regular expressions
keeyre
 
00 ruby tutorial
00 ruby tutorial00 ruby tutorial
00 ruby tutorial
Walker Maidana
 
Ruby training day1
Ruby training day1Ruby training day1
Ruby training day1
Bindesh Vijayan
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Language
zone
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
Raghavan Mohan
 
Subroutines
SubroutinesSubroutines
Subroutines
primeteacher32
 
Vi CheatSheet
Vi CheatSheetVi CheatSheet
Vi CheatSheet
framinazzi
 
P H P Part I, By Kian
P H P  Part  I,  By  KianP H P  Part  I,  By  Kian
P H P Part I, By Kian
phelios
 
Ruby Chapter 2
Ruby Chapter 2Ruby Chapter 2
Ruby Chapter 2
Chaffey College
 
Bioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introductionBioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introduction
Prof. Wim Van Criekinge
 
In-Depth Guide On WordPress Coding Standards For PHP & HTML
In-Depth Guide On WordPress Coding Standards For PHP & HTMLIn-Depth Guide On WordPress Coding Standards For PHP & HTML
In-Depth Guide On WordPress Coding Standards For PHP & HTML
eSparkBiz
 
Strings Objects Variables
Strings Objects VariablesStrings Objects Variables
Strings Objects Variables
Chaffey College
 
Strings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlStrings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perl
sana mateen
 
perltut
perltutperltut
perltut
tutorialsruby
 
Ruby quick ref
Ruby quick refRuby quick ref
Ruby quick ref
Tharcius Silva
 
Ruby cheat sheet
Ruby cheat sheetRuby cheat sheet
Ruby cheat sheet
Tharcius Silva
 
Playfulness at Work
Playfulness at WorkPlayfulness at Work
Playfulness at Work
Erin Dees
 
Write Your Own JVM Compiler
Write Your Own JVM CompilerWrite Your Own JVM Compiler
Write Your Own JVM Compiler
Erin Dees
 
Bash
BashBash
JRuby, Not Just For Hard-Headed Pragmatists Anymore
JRuby, Not Just For Hard-Headed Pragmatists AnymoreJRuby, Not Just For Hard-Headed Pragmatists Anymore
JRuby, Not Just For Hard-Headed Pragmatists Anymore
Erin Dees
 

What's hot (20)

Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
00 ruby tutorial
00 ruby tutorial00 ruby tutorial
00 ruby tutorial
 
Ruby training day1
Ruby training day1Ruby training day1
Ruby training day1
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Language
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
Subroutines
SubroutinesSubroutines
Subroutines
 
Vi CheatSheet
Vi CheatSheetVi CheatSheet
Vi CheatSheet
 
P H P Part I, By Kian
P H P  Part  I,  By  KianP H P  Part  I,  By  Kian
P H P Part I, By Kian
 
Ruby Chapter 2
Ruby Chapter 2Ruby Chapter 2
Ruby Chapter 2
 
Bioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introductionBioinformatica 06-10-2011-p2 introduction
Bioinformatica 06-10-2011-p2 introduction
 
In-Depth Guide On WordPress Coding Standards For PHP & HTML
In-Depth Guide On WordPress Coding Standards For PHP & HTMLIn-Depth Guide On WordPress Coding Standards For PHP & HTML
In-Depth Guide On WordPress Coding Standards For PHP & HTML
 
Strings Objects Variables
Strings Objects VariablesStrings Objects Variables
Strings Objects Variables
 
Strings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlStrings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perl
 
perltut
perltutperltut
perltut
 
Ruby quick ref
Ruby quick refRuby quick ref
Ruby quick ref
 
Ruby cheat sheet
Ruby cheat sheetRuby cheat sheet
Ruby cheat sheet
 
Playfulness at Work
Playfulness at WorkPlayfulness at Work
Playfulness at Work
 
Write Your Own JVM Compiler
Write Your Own JVM CompilerWrite Your Own JVM Compiler
Write Your Own JVM Compiler
 
Bash
BashBash
Bash
 
JRuby, Not Just For Hard-Headed Pragmatists Anymore
JRuby, Not Just For Hard-Headed Pragmatists AnymoreJRuby, Not Just For Hard-Headed Pragmatists Anymore
JRuby, Not Just For Hard-Headed Pragmatists Anymore
 

Viewers also liked

Collaboration On Rails
Collaboration On RailsCollaboration On Rails
Collaboration On RailsJesse Cai
 
1st Chinaonrails Open Course 高级战略
1st Chinaonrails Open Course 高级战略1st Chinaonrails Open Course 高级战略
1st Chinaonrails Open Course 高级战略
Jesse Cai
 
Status Ruby on Rails in China
Status Ruby on Rails in ChinaStatus Ruby on Rails in China
Status Ruby on Rails in China
Jesse Cai
 
Analytics Uibbs 20080709 20080709 (Dashboard Report)
Analytics Uibbs 20080709 20080709 (Dashboard Report)Analytics Uibbs 20080709 20080709 (Dashboard Report)
Analytics Uibbs 20080709 20080709 (Dashboard Report)
Jesse Cai
 
1st Chinaonrails Open Course 开源实践
1st Chinaonrails Open Course 开源实践1st Chinaonrails Open Course 开源实践
1st Chinaonrails Open Course 开源实践
Jesse Cai
 
Chinaonrails Rubyonrails21 Zh
Chinaonrails Rubyonrails21 ZhChinaonrails Rubyonrails21 Zh
Chinaonrails Rubyonrails21 Zh
Jesse Cai
 
程序员0806期敏捷与性能的博弈
程序员0806期敏捷与性能的博弈程序员0806期敏捷与性能的博弈
程序员0806期敏捷与性能的博弈
Jesse Cai
 
Analytics Uibbs 20080709 20080709 (Dashboard Report)
Analytics Uibbs 20080709 20080709 (Dashboard Report)Analytics Uibbs 20080709 20080709 (Dashboard Report)
Analytics Uibbs 20080709 20080709 (Dashboard Report)
Jesse Cai
 

Viewers also liked (8)

Collaboration On Rails
Collaboration On RailsCollaboration On Rails
Collaboration On Rails
 
1st Chinaonrails Open Course 高级战略
1st Chinaonrails Open Course 高级战略1st Chinaonrails Open Course 高级战略
1st Chinaonrails Open Course 高级战略
 
Status Ruby on Rails in China
Status Ruby on Rails in ChinaStatus Ruby on Rails in China
Status Ruby on Rails in China
 
Analytics Uibbs 20080709 20080709 (Dashboard Report)
Analytics Uibbs 20080709 20080709 (Dashboard Report)Analytics Uibbs 20080709 20080709 (Dashboard Report)
Analytics Uibbs 20080709 20080709 (Dashboard Report)
 
1st Chinaonrails Open Course 开源实践
1st Chinaonrails Open Course 开源实践1st Chinaonrails Open Course 开源实践
1st Chinaonrails Open Course 开源实践
 
Chinaonrails Rubyonrails21 Zh
Chinaonrails Rubyonrails21 ZhChinaonrails Rubyonrails21 Zh
Chinaonrails Rubyonrails21 Zh
 
程序员0806期敏捷与性能的博弈
程序员0806期敏捷与性能的博弈程序员0806期敏捷与性能的博弈
程序员0806期敏捷与性能的博弈
 
Analytics Uibbs 20080709 20080709 (Dashboard Report)
Analytics Uibbs 20080709 20080709 (Dashboard Report)Analytics Uibbs 20080709 20080709 (Dashboard Report)
Analytics Uibbs 20080709 20080709 (Dashboard Report)
 

Similar to Ruby_Coding_Convention

Designing Ruby APIs
Designing Ruby APIsDesigning Ruby APIs
Designing Ruby APIs
Wen-Tien Chang
 
Ruby 2.0
Ruby 2.0Ruby 2.0
Ruby 2.0
Uģis Ozols
 
Attributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active recordAttributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active record
.toster
 
BASH Guide Summary
BASH Guide SummaryBASH Guide Summary
BASH Guide Summary
Ohgyun Ahn
 
Bash shell
Bash shellBash shell
Bash shell
xylas121
 
testing add
testing addtesting add
testing add
alind tiwari
 
latest slide
latest slidelatest slide
latest slide
alind tiwari
 
Write your Ruby in Style
Write your Ruby in StyleWrite your Ruby in Style
Write your Ruby in Style
Bhavin Javia
 
Style guideshell
Style guideshellStyle guideshell
Style guideshell
blaap
 
Talk Unix Shell Script
Talk Unix Shell ScriptTalk Unix Shell Script
Talk Unix Shell Script
Dr.Ravi
 
Talk Unix Shell Script 1
Talk Unix Shell Script 1Talk Unix Shell Script 1
Talk Unix Shell Script 1
Dr.Ravi
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
Mufaddal Haidermota
 
04 ruby syntax
04 ruby syntax04 ruby syntax
04 ruby syntax
Walker Maidana
 
390aLecture05_12sp.ppt
390aLecture05_12sp.ppt390aLecture05_12sp.ppt
390aLecture05_12sp.ppt
mugeshmsd5
 
First steps in C-Shell
First steps in C-ShellFirst steps in C-Shell
First steps in C-Shell
Brahma Killampalli
 
Case, Loop & Command line args un Unix
Case, Loop & Command line args un UnixCase, Loop & Command line args un Unix
Case, Loop & Command line args un Unix
Vpmv
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java Programmers
Mike Bowler
 
Jekyll - Liquid for noobs
Jekyll - Liquid for noobsJekyll - Liquid for noobs
Jekyll - Liquid for noobs
Bruno Mendes
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
maheshm1206
 
Coding style of Linux Kernel
Coding style of Linux KernelCoding style of Linux Kernel
Coding style of Linux Kernel
Peter Chang
 

Similar to Ruby_Coding_Convention (20)

Designing Ruby APIs
Designing Ruby APIsDesigning Ruby APIs
Designing Ruby APIs
 
Ruby 2.0
Ruby 2.0Ruby 2.0
Ruby 2.0
 
Attributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active recordAttributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active record
 
BASH Guide Summary
BASH Guide SummaryBASH Guide Summary
BASH Guide Summary
 
Bash shell
Bash shellBash shell
Bash shell
 
testing add
testing addtesting add
testing add
 
latest slide
latest slidelatest slide
latest slide
 
Write your Ruby in Style
Write your Ruby in StyleWrite your Ruby in Style
Write your Ruby in Style
 
Style guideshell
Style guideshellStyle guideshell
Style guideshell
 
Talk Unix Shell Script
Talk Unix Shell ScriptTalk Unix Shell Script
Talk Unix Shell Script
 
Talk Unix Shell Script 1
Talk Unix Shell Script 1Talk Unix Shell Script 1
Talk Unix Shell Script 1
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
04 ruby syntax
04 ruby syntax04 ruby syntax
04 ruby syntax
 
390aLecture05_12sp.ppt
390aLecture05_12sp.ppt390aLecture05_12sp.ppt
390aLecture05_12sp.ppt
 
First steps in C-Shell
First steps in C-ShellFirst steps in C-Shell
First steps in C-Shell
 
Case, Loop & Command line args un Unix
Case, Loop & Command line args un UnixCase, Loop & Command line args un Unix
Case, Loop & Command line args un Unix
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java Programmers
 
Jekyll - Liquid for noobs
Jekyll - Liquid for noobsJekyll - Liquid for noobs
Jekyll - Liquid for noobs
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
 
Coding style of Linux Kernel
Coding style of Linux KernelCoding style of Linux Kernel
Coding style of Linux Kernel
 

Recently uploaded

Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
marufrahmanstratejm
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
Neo4j
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Precisely
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
Ivo Velitchkov
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 

Recently uploaded (20)

Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 

Ruby_Coding_Convention

  • 1. RubyCodingConvention (DRAFT VERSION: 2001/11/01) File Names Directory and File names and Suffixes Ruby source code file/directory name is lower case class/module name with suffix '.rb'. ex. Foo class => foo.rb Bar module => bar.rb FooBar class => foobar.rb (Normal Rule) foo_bar.rb (Rails Rule) Foo::Bar class => foo/bar.rb *1 Libraries non-standard multiple files required by a script should be in one directory, and they should be installed to the standard site-ruby directory or a script's library directory. don't use a current directory for libraries --- it is dangerous. since the directory in which script exists can not be specified portably, it is also not suited for libraries. File Organization • require (if necessary) • include (if necessary) • classes and modules definition • main • testing code(?) using __FILE__ idiom ex: if __FILE__ == $0 <testcode> end Beginning Comment begin - end style for file header or footer. =begin * Name: * Description * Author: * Date:
  • 2. * License: =end using '#' style for class/module and method definitions # using foo bar # # foo bar buz. # class Foo # bar.bar.bar. # class Bar # constructor of Bar. # def initialize(bar = nil) super(bar) end def bar self end end def initialize() end end Indentation Line length Max length is about 80 characters. Wrapping Line • Break after comma • Break after operator Comments Ruby has two comments style: =begin...=end and '#'. You should use =begin...=end for Documentation Comments, and '#' for both Documentation Comments and Implementation Comments.
  • 3. Implementation Comments Block Comments # Here is block comment. # # foo, bar, buz. Single-Line Comments # this is single line comment. ## this is also single line comment. Tailing Comments if a == 2 true # special case else prime?(a) # work only for odd a end Documentation Comments Header/Footer =begin = FooBar library == What's New? ..... .... == Installation ..... .... .... =end In Class/Module # ..... # .... # def foo() ..
  • 4. or ## # ..... # .... # def foo() .. Way of no commenting If you can write simple, short and light scripts, comments may not be necessary. You can let the script itself tell everything, instead of embedding documentation that may confuse readers of your script. Definitions Initialization Ruby variables have no 'definitions'. So, you should initialize variables. One initialization per line level = 0 size = 0 is preferred over level = size = 0 Placement Statements Simple Statements Each line should contain at most one statement. foo = 1 ## Correct bar = 2 ## Correct foo = 1; bar = 2 ## AVOID! Compound Statements if-end, if-else-end, if-elsif-else-end Statements simple example:
  • 5. if <condition> <statements> end more complex example: if <condition> <statements> elsif <condition> <statements> else <statements> end You can put on <condition> after <statements> when <statements> is one-line. <statements> if <condition> block methods `{...}' style: bar.foo(vars){|vars2| <statements> } `do...end' style: bar.foo(vars) do |vars2| <statements> end one-line block: bar.foo(){|var| <statements> } case-when Statements Ruby's case-when (not when-case) does not need 'break'. case foo when condition1 <statements> when condition2 <statements> else <statements> end begin-rescue-end Statements It handles errors (Exceptions).
  • 6. begin <statements> rescue FooError => e <statements> rescue BazError => e2 <statements> rescue <statements> end White Space Blank Lines • Between sections of a source file • Between class and module definitions • Between methods • Before blocks or single-line comments • Between logical sections inside a method to improve readability Blank spaces A keyword followed by a parenthesis should be separated by a space. ex: while (foo.end?) { <statements> } The number of spaces should be balanced. a+b ## Correct a + b ## Correct a+ b ## AVOID! a +b ## AVOID! (Erroneous: interpreted as a(+b)) a += b + c a = (a + b) / (c * d) a = b foo(quot;fooquot; + buz + bar) Naming Conventions Classes/Modules class and module names should be nouns; in mixed case with the first letter of each internal word capitalized. ex: class Raster, class Raster::ImageSprite
  • 7. Methods Methods should be verbs. All lower case ASCII letters with words separated by underscores ('_') ex. run(), run_fast(), obj.background_color() Variables variable names should be all lower case ASCII letters with words separated by underscore ('_') ex: i = 1 some_char = SomeChar.new() table_width = 0.0 Constants *2 constants should be all upper case with words separated by underscores ('_'). ex: MIN_LENGTH = 1 DEFAULT_HOST = quot;foo.example.comquot; Omission Speaking of 'Connection Pool' as a variable, you should decide to prefer name by scope such as the following... • 'conpool' for local scope (such as local variable) • '@connection_pool' for class scope (such as instance variable) Pragmatic Programming Practices Using attr_* to access def foo() @foo end attr_reader :foo Without Parenthesis Some methods are used without parenthesis. • require ex. require 'foo/bar' • include
  • 8. ex. include FooModule • p ex. p foo • attr_* ex. attr_reader :foo, :bar Reduce repetition When successive lines of a script share something, x = ModuleA::ClassB::method_c( a ) y = ModuleA::ClassB::method_d( b ) (-- 'function' => 'method' --) you should make it like this: cb = ModuleA::ClassB x = cb::method_c( a ) y = cb::method_d( b ) You can also do: include ModuleA x = ClassB::method_c(a) y = ClassB::method_d(b) Code Example Ruby Source File Example =begin blahdy/blah.rb $Id:$ Copyright (c) 2001 TAKAHASHI Masayoshi This is free software; you can copy and distribute and modify this program under the term of Ruby's License (http://www.ruby-lang.org/LINCENSE.txt) =end # # module description goes here. # # @version: 1.82 # @author: TAKAHASHI Masayoshi #
  • 9. module Blahdy class Blah < SomeClass # A class implementation comment goes here. # CLASS_VAR1 documentation comment CLASS_VAR1 = 1; # CLASS_VAR2 documentation comment that happens # to be more than one line length. # CLASS_VAR2 = 1; # ...constructor Blah documentation comment... # def initialize() ## ...implementation goes here... end # ...method do_something documentation comment... # def do_sometiong() ## ...implementation goes here... end # ...method do_something_else documentation comment... # # @param some_param description # def do_something_else(some_param) ## ...implementation goes here... end end end *1 any arguments? *2 Huh, is there a reasonable background to distinguish constants from a class name which is a constant at the same time?