I have a method taking only one parameter:
def my_method(number)
end
How can I raise an error if the method is called with a number < 2
?
And generally, how can I define conditions on a method's parameter?
For example, I want to have an error when calling:
my_method(1)
You can add guard in the beginning of function and raise an exception if arguments are not valid. For example:
def my_method(number)
fail ArgumentError, "Input should be greater than or equal to 2" if number < 2
# rest of code follows
# ...
end
# Sample run
begin
my_method(1)
rescue => e
puts e.message
end
#=> Input should be greater than or equal to 2
You could define custom exception class if you don't want to use the ArgumentError
If you are building something like a framework, then, you can make use of meta-programming techniques to intercept method invocations and apply some validations. Refer Executing code for every method call in a Ruby module. You may have to come up with some kind of DSL to express those validations - a typical example of validation DSL is Active Record Validations in Rails.
In summary, for day-to-day use cases, simple raise
(or fail
) and rescue
should suffice. The meta-programming and DSL based validations are needed only if you are building a general purpose framework.
You'll have to check the condition and raise it inside method body. There's no builtin option like you want.
You could do this:
def my_method arg, dummy = (raise ArgumentError, "arg < 2" if arg < 2)
puts "arg=#{arg}"
end
my_method 3
# arg=3
my_method 1
# ArgumentError: arg < 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With