Unique Marketing, Guaranteed Results.

Ruby newbie iteration musings

May 5th, 2009 by hals

First off I must note how nice it is that semicolons, and several other punctuation items, are optional.

Another nice thing I have been introduced to is the iterator. In most cases it completely replaces the old for loop. 

var.each {|x| ….}     

or

for x in var {……}

seem much cleaner and easier to write than

for (int i=0; i<10; i++) {…; …;}

Extending this makes it handy to work with multiple parameters. Let’s say that you want to pass in a variable number of arguments, that can also be hashes.

One way of working with them in the method would be as follows:

class Ema

def initialize(p1, p2, *p3)  # the ‘*’ will push arguments 3…n into p3 as an array

# then you might access parameter3 with one of the following .each variants:

def showMe

    @p3.each do |s|    #this gives you each element of the array - 

      puts “  p3: s = #{s}”

        s.each_key do |y|     #each element is a hash, so this gives you the keys

          puts ”     #{y} = #{s[y]}”

        end

        s.each do |y,z|       #this will give you the key, value pairs

          puts ”     #{y} = #{z}”

        end

        s.each do |r|        #and this gives you the key,value in an array

          puts ”     #{r[0]} = #{r[1]}”

        end

    end

end

 a = Ema.new(“one”, “two”, {“apple” => 3}, {“pear” => 1}, {“grape” => 5}, {“kiwi” => 33})

a.showMe

Be Sociable, Share!
Filed under: Programming — Tags: , — hals @ 11:13 am on May 5, 2009

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Copyright © 2005-2011 PMA Media Group. All Rights Reserved