IRohitable | August 2012

Ruby Notes - 2

by Rohit 31. August 2012 21:35

In this post of the Ruby Notes series:

Some unique control structures in Ruby

 

 

Ruby tries to make code more concise and readable where ever possible. Some new controls structures like unless , until and each make code less verbose and more understandable.

if not vs. unless:

Take for instance this example where we use age old If to check for negation:

class Person
     attr_accessor :age


     def age
       @age
     end


     def age=(num)
        @age = num

        if not @age > 18
            puts 'Person not eligible for driving'
        end
     end

end

 

Now the same example using Unless. Not only unless makes the negation easy to understand but also makes it more concise.

class Person 
    attr_accessor :age


    def age 
      @age 
    end


    def age=(num) 
       @age = num 

       unless @age > 18 
          puts 'Person not eligible for driving' 
       end 
    end 

end

 

With unless, the body of the statement is executed only if the condition is false. Not only the latter version is one token shorter than if not, it takes less mental energy to understand once you get used to it.

 

while vs. until:

In exactly the same way that if has unless, while has a substitute as until. An until loop keeps going until its conditional part becomes true.

 

i = 0 
while i <= 10 
  i += 1 
end 

puts i

 

 

i = 0 
until i == 10 
  i += 1 
end 

puts i

 

 

for vs. each

 

customers = ['John','Alex','Peter']

for name in customers 
   puts name 
end

 

 

customers = ['John','Alex','Peter']

customers.each do |name| 
   puts name 
end

 

Why use each over for? Because, for internally calls each so why complicate things and not use each directly.

 

 

Previous post of Ruby Notes Series: Ruby Notes - 1

 

Tags: ,

Ruby on Rails | Technology

Ruby Notes : 1

by Rohit 24. August 2012 18:17

 

This is the first post of Ruby Notes series. This series and the later, Rails Notes, is a collection of my personal learning notes prepared while learning Ruby and Rails. These notes are the extract of the several books I referred while learning Ruby. These notes were lying on my shelf from quite some time when one bright sunny day I realised to publish them in the hope to help large number of beginners and enthusiasts needing quick reference to relevant topics only.

In this post:

  1. The Ruby style of Coding.
  2. Proper use of Comments.
  3. When to use Parentheses and when to ignore?
  4. How much code in one line? Single-line or multi-line.

THE RUBY STYLE OF CODING

The Ruby style of coding is built on few simple ideas like:

  • The code should be clear and itself tell the reader what exactly it is trying to do.
  • The code should be concise.

To adapt these simple ideas into practice, Ruby stresses on Convention over Configuration from the very start. In Ruby, you indent your code with two spaces per level. The rule is not to use Tabs for indentation.

The Ruby naming convention in short says: Camels for Classes, Snakes everywhere.

This means the Class names should use Camel casing while the rest of the things like methods, arguments and variables should use lower case. For example:

class Customer   
   attr_accessor  :name,  :address,  :place

 
   def initialize(name, address, place)
       @name = name
       @address = address
       @place = place
   end


   def name_length
       puts name.size
   end
end

For constants there is a mixed belief. However, the Ruby community recommends all uppercase with words separated by underscore. For example:

ANNUAL_DISCOUNT = 20

 

PROPER USE OF COMMENTS

Ruby's philosophy says: "Good code speaks for itself". Therefore, use comments only when necessary not just everywhere.

(1) Keep background information separate from instructions:

# Author: 
# Copyright 2012:
#
# An example of Ruby class

 

(2) Not every line requires comment:

number += 1  # Add one to number

 

(3) An example of proper use of comment:

return 0 if divisor == 0  # Avoid division by zero

 

WHEN TO USE PARENTHESES AND WHEN TO IGNORE?

There is no rigid rule but this is what the Ruby community prefers:

(1) Use Parentheses with the arguments. For example:

def increment_number (number)
   number += 1
   puts number
end

(2) Ignore Parentheses in this type of situation:

def name_length()
   puts name.size
end

 Use instead

def name_length
   puts name.size
end

 

HOW MUCH CODE IN ONE LINE? SINGLE-LINE OR MULTI-LINE?

Preferably one code statement per line is recommended for good readability. However, in certain situations you can fold cold block into one if it doesn't compromise readability. Note how this code can be written with folded block of code without compromising readability:

 

Style 1:

5.times do |num|
  puts "The number is #{num}"
end

Style 2:

5.times { |num|  puts "The number is #{num}"  }


Technorati : ,
Del.icio.us : ,

Tags: ,

Ruby on Rails

About Rohit Prakash

Software Craftsman @ Fortune 100 Company. Technical Reviewer of few programming books.

A Single, Writer, Reader and Adventurist.

You can reach me at:

rohit [at] irohitable.com

-----------------------------------------

LinkedIn:

in.linkedin.com/in/rohitpkhare

Twitter:

@BuzzRohit

-----------------------------------------

Month List

Protected by Copyscape Web Plagiarism Software