IRohitable | Ruby Notes - 2

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

Add comment

biuquote
  • Comment
  • Preview
Loading

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