Different Block Forms

Blocks or simply chunks of code as in the last example may be existing variables which changes after that same variable passes thought the block, giving it a new value. Blocks may also be used to return a needed value to the method as in the last example, the resulting value of the last expression the data was exposed to was returned back to the method as the pre-set value of the yield statement till the condition which was the set maximum value of the Fibonacci Series that was set to 1000. This is why the find method which is used for array class objects work. The method find is actually defined in the enumerable module thrown into the array class mix. The Next Post, shows a sample code using the find method.

Sample Code using find :

class Array
def find
for a in 0…size
value = himself[a]
return value in yield(value)
end
return nil
end
end
[1, 3, 5, 7, 9].find {|v| v*v >30}

The code has elements passed successively to the attached block which returns true if the method sends in a corresponding element. If none match, then nil is returned which is a very good example of how to best utilize iterators. The Array class is simply doing what it was designed to which is to access the contents of an array leaving the application to do what it is supposed to do which in this case is to find entries that satisfies a set criteria.

This entry was posted in Development, Programming Basics and tagged , . Bookmark the permalink. Comments are closed, but you can leave a trackback: Trackback URL.