这是代码,但其中很多是无关紧要的:
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 - 例如“这是一条自定义错误消息”。
我已经为此苦苦挣扎了好几个小时,但我已经束手无策了。我是一个相对初学者,所以请记住这一点。
谢谢。