programming.nbk: Home | Index | Next Page: Ruby: case | Previous Page: Ruby: Arrays


 Ruby: Blocks

A block is a chunk of code that gets passed to a method, which then executes the block's code with the yield keyword.

The block definition is started on the same line as the method call. If block fits on a single line, it is contained in curly braces {}. If the block extends over multiple lines it startes with do and ends with end.

A block may only appear in the source code after a method call, starting on the same line as the method call.

Example:

    def threeTimes
        yield
        yield
        yield
    end
    threeTimes { puts "Hello" }

The block can have arguments. They appear in the block definition between pipe characters:

    def fibUpTo(max)
        i1, i2 = 1, 1        # parallel assignment
        while i1 <= max
            yield i1
            i1, i2 = i2, i1+i2
        end
    end
    fibUpTo(1000) { |f| print f, " " }

The block can return a value. This is returned to the method as the value of the yield:

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

Blocks are not methods themselves, but can be converted into methods with the lambda of the Kernel module:

    toast = lambda do  
      puts 'Cheers'  
    end  
    toast.call

programming.nbk: Home | Index | Next Page: Ruby: case | Previous Page: Ruby: Arrays


Notebook exported on Monday, 7 July 2008, 18:56:06 PM Eastern Daylight Time