有人可以解释星号之间发生的事情吗?
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
答案 0 :(得分:1)
begin
和rescue
语句是在ruby中实现exception handling的一种方式。
begin
到rescue
的所有内容都受到保护。如果在执行此代码块期间发生异常,则控制权将传递到rescue
和end
之间的块。
换句话说,代码确保当您调用nil
不存在的方法时,您的程序不会中断。
nil.some_method_nil_doesnt_know_about
导致异常(异常应该为NoMethodError
),因此rescue
块中的代码将被执行,而不是程序崩溃。
assert_equal NoMethodError, ex.class
确保异常确实是NoMethodError
,下一行是确保错误消息匹配。