简体   繁体   English

Ruby Koans步骤6

[英]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

The begin and rescue statements are a way of implementing exception handling in ruby. beginrescue语句是在ruby中实现异常处理的一种方式。

Everything from begin to rescue is protected. beginrescue一切都受到保护。 If an exception occurs during the execution of this block of code, control is passed to the block between rescue and end . 如果在执行此代码块期间发生异常,则将控制权传递给rescueend之间的块。

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不存在的方法时程序不会中断。

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. nil.some_method_nil_doesnt_know_about引起异常(该异常NoMethodError ),因此将执行rescue块中的代码,而不是程序崩溃。

assert_equal NoMethodError, ex.class is making sure the exception indeed was NoMethodError , and the next line is making sure the error messages match. assert_equal NoMethodError, ex.class确保异常确实是NoMethodError ,而下一行确保错误消息匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM