What are the reserved words BEGIN or END used for in Ruby?

reserved-words, ruby

Solution

As all keywords `BEGIN` and `END` are documented as public instance methods of `Object` (even though you won't see them returned from `Object.public_instance_methods`)

BEGIN Designates, via code block, code to be executed unconditionally before sequential execution of the program begins. Sometimes used to simulate forward references to methods.

puts times_3(gets.to_i)

BEGIN {
  def times_3(n)
    n * 3
  end
}

END Designates, via code block, code to be executed just prior to program termination.

END { 
  puts "Bye!" 
}

Some more detailed explanation from Programming Ruby The Pragmatic Programmer's Guide

BEGIN and END Blocks

Every Ruby source file can declare blocks of code to be run as the file is being loaded (the BEGIN blocks) and after the program has finished executing (the END blocks).

BEGIN {   
  begin code 
}

END {
  end code 
}

A program may include multiple BEGIN and END blocks. BEGIN blocks are executed in the order they are encountered. END blocks are executed in reverse order.

Problem

This is a very hard to find word because in most cases they are not sensitive during a search. The best I could find outside of documentation is a test in IRB. ``` BEGIN{puts x = 10} 10 ```

Original source