Define conditions for a method parameter

I have a method that takes only one parameter:

def my_method(number) end 

How can I raise an error if the method is called with number < 2 ? And anyway, how can I define the conditions for a method parameter?

For example, I want to have an error when calling:

 my_method(1) 
+5
source share
3 answers

You can add guard at the beginning of the function and throw an exception if the arguments are invalid. For instance:

 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 can define a custom exception class if you do not want to use ArgumentError


If you are building something like a framework, then you can use metaprogramming methods to intercept method calls and apply some validations. Refer to Code Execution for each method call in the Ruby module . You may need to come up with some kind of DSL to express these checks - a typical example of a DSL check is Active Record Validations in Rails.

In general, for everyday use cases just raise ( or fail ) and rescue enough. Verifications based on metaprograms and DSL are only necessary if you are creating a general-purpose infrastructure.

+6
source

You will need to check the state and raise it inside the method body. There is no built-in option as you want.

+1
source

You can do it:

 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 
+1
source

Source: https://habr.com/ru/post/1240007/


All Articles