Pages

Friday, April 9, 2010

Containers, Blocks, and Iterators

Category    Ruby, Programming

Containers are objects that hold references to one or more other objects.

 
 

Arrays

 
 

A Ruby array holds a collection of object references identified by a non-negative integer index.

 
 

In an array class, [] is a method which accesses elements by index.

 
 

def [] (key)

if key.kind_of? (Integer)

result = @songs[key]

else

for I in 0…@songs.length

result = @songs[i] if key == aSong.name

end

return result

end

 
 

Hashes

 
 

Compared with arrays, hashes have one significant advantage: they can use any type of object as an index. However, they also have a significant disadvantage: their elements are not ordered, so you cannot use a hash as a stack or queue.

 
 

Blocks and Iterators

 
 

A better way of the [] mehtod:

 
 

def [] (key)

return @songs[key] if key.kind_of?(Integer)

return @songs.find { |aSong| aSong.name == key }

end

 
 

An iterator is a method that invokes a block of code repeatedly.

 
 

The uses of a block

A block is often the target of an iterator.

A block can be used to define a chunk of code that must run under some kind of transactional control.

 
 

class File

def File.openAndProcess(*args)

f = File.open(*args)

yield f

f.close()

end

end

 
 

File.openAndProcess("textfile", "r") do |aFile|

print while aFile.gets

end

 
 

In this way, the responsibility of closing an open file has been passed from the user of the file object to the file themselves.

 
 

The do…end block has lower precedence than {...}.

 
 

The method Kernel::block_given? returns true if a block is associated with the current method.

 
 

If the last parameter in a method definition is prefixed with an ampersand, Ruby looks for a code block whenever the method is called. The code block is converted to an object of class Proc and assigned to the parameter.

 
 

What is closure in a programming language?

Iterators

 
 

find, each, and collect

 
 

All the each iterator does is yield successive element of its collection.

In the collect iterator, the results returned by the block are used to construct a new array.

No comments: