[英]Ruby Methods: how to return an usage string when insufficient arguments are given
After I have created a serious bunch of classes (with initialize methods), I am loading these into IRb to test each of them. 在我创建了一大堆类(使用初始化方法)之后,我将这些类加载到IRb中以测试它们中的每一个。 I do so by creating simple instances and calling their methods to learn their behavior.
我这样做是通过创建简单的实例并调用他们的方法来学习他们的行为。 However sometimes I don't remember exactly what order I was supposed to give the arguments when I call the .new method on the class.
但是有时我不记得在我在类上调用.new方法时我应该给出参数的确切顺序。 It requires me to look back at the code.
它需要我回顾一下代码。 However, I think it should be easy enough to return a usage message, instead of seeing:
但是,我认为返回使用消息应该很容易,而不是看到:
ArgumentError: wrong number of arguments (0 for 9)
So I prefer to return a string with the human readable arguments, by example using "puts" or just a return of a string. 所以我更喜欢返回一个带有人类可读参数的字符串,例如使用“puts”或只返回一个字符串。 Now I have seen the rescue keyword inside begin-end code, but I wonder how I could catch the ArgumentError when the initialize method is called.
现在我在开始结束代码中看到了rescue关键字,但我想知道在调用initialize方法时如何捕获ArgumentError。
Thank you for your answers, feedback and comments! 感谢您的回答,反馈和意见!
It is possible to hook into object creation by overriding the Class#new
method eg 可以通过重写
Class#new
方法来挂钩对象创建,例如
class Class
# alias the original 'new' method before overriding it
alias_method :old_new, :new
def new(*args)
return old_new(*args)
rescue ArgumentError => ae
if respond_to?(:usage)
raise ArgumentError.new(usage)
else
raise ae
end
end
end
This overriden method calls the normal new
method but catches ArgumentError
and if the class of the object being created provides a usage
method then it will raise an ArgumentError
with the usage message otherwise it will reraise the original ArgumentError
. 这个overriden方法调用普通的
new
方法,但是捕获ArgumentError
,如果正在创建的对象的类提供了一个usage
方法,那么它将引发带有用法消息的ArgumentError
,否则它将重新加入原始的ArgumentError
。
Here is an example of it in action. 以下是它的实例。 Define a
Person
class: 定义
Person
类:
class Person
def initialize(name, age)
end
def self.usage
"Person.new should be called with 2 arguments: name and age"
end
end
and then try and instantiate it without the required arguments: 然后尝试在没有必需参数的情况下实例化它:
irb(main):019:0> p = Person.new
ArgumentError: Person.new should be called with 2 arguments: name and age
from (irb):8:in `new'
from (irb):22
Note : this isn't perfect. 注意 :这并不完美。 The main problem being that it is possible that the
ArgumentError
we catch has been caused by something other than an incorrect number of arguments being passed to initialize
which would lead to a misleading message. 主要的问题是我们捕获的
ArgumentError
可能是由于传递给initialize
的参数数量不正确而导致误导性消息引起的。 However it should do what you want in most cases. 但是在大多数情况下它应该做你想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.