5

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)
sawa
  • 165,429
  • 45
  • 277
  • 381
Graham Slick
  • 6,692
  • 9
  • 51
  • 87

3 Answers3

6

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.

Community
  • 1
  • 1
Wand Maker
  • 18,476
  • 8
  • 53
  • 87
  • 1
    You don't have to call `new`, just pass the exception class and the message, i.e. `raise ArgumentError, "Input should be ..."` (or `fail` according to the Ruby style guide) – Stefan Jan 06 '16 at 16:25
  • @Stefan Thanks a lot. I updated the code. Appreciate the inputs you keep leaving behind on various posts. – Wand Maker Jan 06 '16 at 16:30
1

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

Babar Al-Amin
  • 3,939
  • 1
  • 16
  • 20
1

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
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100