[ next ] [ prev ] [ contents ] [ up to The Top Ten Reasons I Like Ruby ] Invitation To Ruby

Reason 4 -- Blocks and Closures

Blocks and closures are an extremely useful concept. Uses for blocks and closures keep popping up all over the place.

Some possibilities are ...

Iterating

    5.times { |i| puts "#{i}: Hello!" }

Callbacks (see example)

    light = LightBulb.new
    gui_button.when_pressed { light.turn_on }

Delayed Execution

    upon_program_exit { db.disconnect }

Resource Management (see example)

    sql = "SELECT first_name FROM people WHERE last_name = 'Weirich'"
    db.select_all(sql) { |row|
      puts "#{row[0]} is a Weirich"
    }

Transaction Control (see example)

    db.transaction {
      db.do("UPDATE people SET ...")
      db.do("UPDATE addresses SET ...")
    }

Critical Region Management (see example)

    lock(semaphore) {
      queue.add(data_element) # Critical Region
    }

Thread Creation (see example)

    t = Thread.new {
      10.times { |i|
        puts "HI (#{i})"
         sleep 0.2 
      }
    }

Lazy Evaluation (see example)

    def lazy_list_of_squares(n)
      [n*n, proc { lazy_list_of_squares(n+1) }]
    end

Unusual Control Structures (see example)

    when_logging { puts "Entering new code" }

Really Unusual Control Structures

    choose (proc { try_first_path },
            proc { try_second_path })

Creating Continuations (see example)

    callcc { |continuation|
      continuation.call
      puts "Never called"
    }
    puts "Continuing"

Coroutines (see example)

    co = Coroutine.new {
      5.times {
        do_some_work
        co.switch_to(other)
      }
    }
    co.start


[ next ] [ prev ] [ contents ] [ up to The Top Ten Reasons I Like Ruby ] Copyright 2002 by Jim Weirich.
All rights reserved.