[ next ] [ prev ] [ contents ] [ skip to So ... What is Ruby? ] [ up to First Example ] Invitation To Ruby

Introducing Blocks

Open/Close is a pain

  • It is really easy to forget to call close after an open
  • An exception could cause the close to be skipped.

countfilelines2.rb

  1: #!/usr/bin/env ruby
  2: 
  3: require 'countlines2'
  4: 
  5: for filename in ARGV
  6:   open(filename) do |file|
  7:     printf "%-20s %4d\n",
  8:       filename, filelines(file)
  9:   end
 10: end

  1: # Where open might look like this
  2: # (simplified view)
  3: def open(filename)
  4:   file = do_open_file(filename)
  5:   yield(file)
  6: ensure
  7:   file.close if file
  8: end

  • [6] open can take an optional block
    • A block is code between do / end or { / }
    • It is similar to an anonymous function (i.e. a function with no name)
    • It can have arguments (e.g. |file|)
  • [6-9] open will internally
    • open the file
    • call the block, passing in the newly created file
    • close the file object

There is no way to forget the close call.

  • We only have to write close once (in the open function)

Blocks are extremely powerful

  • Any function (or method) in Ruby can take a block argument.

We will see more examples of blocks in a little bit.

.



[ next ] [ prev ] [ contents ] [ skip to So ... What is Ruby? ] [ up to First Example ] Copyright 2002 by Jim Weirich.
All rights reserved.