Blocks – Example

Below, we find sample code which uses block to return the values of the Fibonacci number Series.

def fibMax(max)
a1, a2 =1,1 # variables that are assigned parallel values
while a1 <= max
yield a1
a1, a2 = a2, a1+a2
end
end
fibMax(1000) {|f| print f, ” “}

The above code gives us the value of the Fibonacci series numbers till the number 1000 which is the set maximum number to reach.

Sample Code Output:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

The above example shows how the block(chunk of code) processed the Fibonacci Series of numbers, returning only those that fell within the set limit of 1000.

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