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.