← Back to Ruby Operators

BEGIN and END Blocks

The BEGIN { ... } block is a block of code that is run before any other code in the file. The END { ... } block is then a block of code that is run after the rest of the file has run.

This isn't something you can expect to see much in "regular" Ruby code, but it is utilizied in some Ruby one-liners.

Here is one from the linked one-liner for counting the number of 2nd-column duplicates:

$ cat duplicates.txt
abc  7   4
food toy ****
abc  7   4
test toy 123
good toy ****

$ ruby -rset -ane 'BEGIN{s=Set.new}; s.add($F[1]);
                   END{puts s.length}' duplicates.txt
2 # '7' and 'toy'

References