My Ruby coding style
2011-03-23 21:04:35
2011-03-18 18:02:26
Autor: Sony Santos
https://gigawiki.com/sony/my-ruby-coding-style
Permalink: https://gigawiki.com/965
assunto = ruby; language = english
- 2 spaces (not tab) identations;

- use ||&&! instead of orand and not

- use unless instead of if !

- use until instead of while !

- use dup instead of clone

- use yield instead of Procs

- use alias_method instead of alias (Motivation)

- in method calls, avoid parenthesis whenever possible.
Exceptions:
  1. before block: meth(args) { code }  instead of meth args { code } 
  2. as param: meth1 arg1, arg2, meth2(argX, argY, argZ) instead of meth1 arg1, arg2, meth2 argX, argY, argZ
  3. around expressions: meth(a ? b : c) instead of meth a ? b : c
  4. before method chaining: meth1(a).meth2 instead of meth1 a.meth2
  5. after super: super(a, b, c) instead of super a, b, c

- use symbols instead of strings whenever possible (in case of immutable strings), specially in hash keys. Use to_s when necessary

- in default parameteres, use nil instead of ''. Example: def fn astring = nil. Use to_s when necessary. Motivation: if astring is better than unless astring.empty?.

- within defs, duplicate arguments to avoid then be overwritten.
Example:
class X
  def fn a
    # uses a copy of a
    a = a.dup

    # modifies a with no worries
    a.delete.format.kill.zerofill.add(rand(42)).scramble
  end
end

a = 'hihaha'
X.new.fn a
puts a           #=> 'hihaha'

Stay tuned with precedences! They rules the exceptions.

- if you do the right way, you avoid unnecessary remarks to explain the exceptions.
blog comments powered by Disqus
Login:
Senha:
Para logar, você precisa ter o Javascript habilitado.