Ruby Koans第6步

时间:2016-04-20 14:39:10

标签: ruby

有人可以解释星号之间发生的事情吗?

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

1 个答案:

答案 0 :(得分:1)

beginrescue语句是在ruby中实现exception handling的一种方式。

  

beginrescue的所有内容都受到保护。如果在执行此代码块期间发生异常,则控制权将传递到rescueend之间的块。

换句话说,代码确保当您调用nil不存在的方法时,您的程序不会中断。

nil.some_method_nil_doesnt_know_about导致异常(异常应该NoMethodError),因此rescue块中的代码将被执行,而不是程序崩溃。

assert_equal NoMethodError, ex.class确保异常确实是NoMethodError,下一行是确保错误消息匹配。