0

这是代码,但其中很多是无关紧要的:

class BankAccount

def initialize(first_name, last_name)
    @first_name = first_name
    @last_name = last_name
    @balance = 0
end

def public_deposit(amount)
    @balance += amount
end

def protected_deposit(amount)
    @balance += amount
end
protected :protected_deposit

def private_deposit(amount)
    @balance += amount
end
private :private_deposit

def call_private_deposit(amount)
    private_deposit(amount)
end

def call_protected_deposit(amount)
    protected_deposit(amount)
end

#To show that you can't call a private method with a different instance of the same class.
def private_add_to_different_account(account, amount)
    account.private_deposit(amount)
end

#To show that you can call a protected method with a different instance of the same class.
def protected_add_to_different_account(account, amount)
    account.protected_deposit(amount)
end
end

我使用“load './visibility.rb'”将此代码加载到 irb 中,然后创建一个实例:

an_instance = BankAccount.new("Joe", "Bloggs")

然后,我通过键入以下内容生成 NoMethodError:

an_instance.protected_deposit(1000)

这将返回 NoMethodError。这是故意的。但是,我想要返回的是自定义消息,而不是标准的 NoMethodError - 例如“这是一条自定义错误消息”。

我已经为此苦苦挣扎了好几个小时,但我已经束手无策了。我是一个相对初学者,所以请记住这一点。

谢谢。

4

1 回答 1

0

您可以挽救错误:

def call_protected_method
  instance = BankAccount.new("Joe", "Bloggs")
  instance.protected_deposit(1000)
rescue NoMethodError
  puts "You called a protected method"
end

如果您想返回自定义消息,您可以挽救错误并引发您自己的自定义异常。Ruby 允许您定义自己的异常类。但我无法想象你为什么要这样做。您已经有一个内置的异常来处理这个问题。

于 2014-10-05T22:27:16.497 回答