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

blog comments powered by Disqus

About Rohit

I have a tremendous passion for software. My day job at a Fortune 100 company exposes me to all sorts of .NET and SQL Server tasks, but my passion drives me to explore other technologies as well. I recently fall in love with Ruby on Rails and in my spare time trying to explore it. Previously I have worked on PHP as well.

I am one of the technical reviewer of Aptana Studio Beginner's Guide which recently got published through Packt Publishing.

My personal blog is with the name My Days Uncovered
 
You can either use Contact Form or mail me directly at:
 
rohit [at] irohitable [dot] com

Month List