Metro Diji
Metro Diji

Reputation: 19

Ruby Koans Step 6

Can someone explain what is happening between the asterisks?

require File.expand_path(File.dirname(__FILE__) + '/edgecase')

class AboutNil < EdgeCase::Koan
  def test_nil_is_an_object
    assert_equal true, nil.is_a?(Object), "Unlike NULL in other languages"
  end

  def test_you_dont_get_null_pointer_errors_when_calling_methods_on_nil
    # What happens when you call a method that doesn't exist.  The
    # following begin/rescue/end code block captures the exception and
    # make some assertions about it.
    # ****************************************

    begin
      nil.some_method_nil_doesnt_know_about
    rescue Exception => ex
      # What exception has been caught?
      assert_equal NoMethodError, ex.class

      # What message was attached to the exception?
      # (HINT: replace __ with part of the error message.)
      assert_match(/undefined method `some_method_nil_doesnt_know_about' for nil:NilClass/, ex.message)

    # ****************************************
    end
  end

Upvotes: 0

Views: 201

Answers (1)

Noam Hacker
Noam Hacker

Reputation: 4825

The begin and rescue statements are a way of implementing exception handling in ruby.

Everything from begin to rescue is protected. If an exception occurs during the execution of this block of code, control is passed to the block between rescue and end.

In other words, the code is making sure your program won't break when you call a method that doesn't exist for nil.

nil.some_method_nil_doesnt_know_about is causing an exception (the exception should be NoMethodError), therefore the code in the rescue block will be executed, instead of the program crashing.

assert_equal NoMethodError, ex.class is making sure the exception indeed was NoMethodError, and the next line is making sure the error messages match.

Upvotes: 1

Related Questions