Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define conditions on a method's parameter

Tags:

methods

ruby

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)
like image 568
Graham Slick Avatar asked Jan 06 '16 16:01

Graham Slick


3 Answers

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.

like image 102
Wand Maker Avatar answered Nov 10 '22 00:11

Wand Maker


You'll have to check the condition and raise it inside method body. There's no builtin option like you want.

like image 28
Babar Al-Amin Avatar answered Nov 10 '22 00:11

Babar Al-Amin


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
like image 40
Cary Swoveland Avatar answered Nov 10 '22 00:11

Cary Swoveland