Thursday, 28 May 2015

List of Common mistakes in Ruby

Always use spaces around operators, after commas, colons and semicolons, around { and before }. White space might be (mostly) irrelevant to the Ruby interpreter, but its proper use is the key to writing easily readable code. Also it makes the design more readable and code much cleaner.

product = 1 * 2
array = [1, 2, 3, 4, 5] { |a| a + 2 }

There should be no spaces after (, [ or before ], ) these brackets.

['ankur', 'vyas']
sum(a, b)

Also don't use spaces in while providing the range.

Use 5..9 over 5 .. 9
Use 'a'..'z' over 'a' .. 'z'

When using switch case statements use the following indentation.

  when input = '+'
    puts 'The operation is addition'
  when '-'
    puts 'The operation is subtraction'
  when '*'
    puts 'The operation is multiplication'
    puts 'The operation is division'

Use following indentation if the parameters exceeds to more than one line.

def send_mail(source)
  Mailer.deliver( to: '',
                  from: '',
                  subject: 'Message subject',
                  body: source.text)

Use splat for better assignments.

element_1, *other_elements = ['a', 'n', 'k', 'u', 'r']

If only 2 conditions are present use the ternary operators.

var_1 = condition ? assignment_1 : assignment_2

If you are setting a variable using the if condition the use following syntax.

variable_result = if condition_1
                  else_if condition_2

Avoid return statements at the end of the line. In ruby the last line of the method is returned.

Use snake case for all the ruby variables.

variable_1, some_variable

Use camel case for class names.

ClassOne, ClassTwo

Use screaming snake case for the constants' names.


Use %w for the string arrays and %i for the symbol arrays.

STATUS_MAP = %w(open closed draft paid)
SYMBOL_MAP = %i(symbol1 symbol2 symbol3)

Use interpolation over concatenation.

Use "#{string_1} < #{string2} >" over string_1 + '<' + string2 + '>'

Assign single quotes to the string which does not have interpolation.

Use 'string 1' over "string 1"

Do not use the word partial when you don't want to pass some variables in it.

Use render 'partial_1' over render partial: 'partial_1'


No comments:

Post a Comment