Ruby PlaygroundRuby Tutorial
UI ThemeDark

Lesson 23 of 23 · Ruby 4.1 development

Recognize alias, undef, BEGIN and END

Identify less common forms and their effect on execution.

Development course: behavior may change with future runtime updates.

Learn

alias introduces another name for an existing method at that point in the program. undef makes a method unavailable through that class. These forms affect an interface, so ordinary method definitions are often clearer when no aliasing is needed. The respond_to? method checks whether an object offers the named method.

BEGIN executes before the main body of a Ruby script. END registers work for normal Ruby process exit. The browser playground evaluates code in a Worker that the host later terminates, rather than shutting down a Ruby command-line process normally. Use a local Ruby script when investigating process-exit behavior; use ensure for cleanup during normal Ruby control flow.

Example

BEGIN { puts "start" }
class Message
  def text
    "hello"
  end
  alias original_text text
  undef text
end
puts Message.new.original_text
p Message.new.respond_to?(:text)
END { puts "finish" }

Experiment

  • Predict which names are callable on each class. Remove undef text and compare how the subclass interface changes. Does the superclass change?

  • Predict both calls. Move the alias line below the second text definition and compare which implementation message uses.

  • Predict the order of the printed lines. Move BEGIN below the second puts and run again. How does BEGIN differ from an ordinary block at that position?

Explore the official manual

Ruby 4.1.0 · development · Example

Ready to run

Output

Run the code to see what happens.