Windor C
Windor C

Reputation: 1120

Is there an elegant way in Ruby which acts like `require` in Scala?

What I want to do is to make sure that arguments meet some conditions, if not, raise errors.

like this(let's say I want to make sure n > 0):

def some_method(n)
  raise "some error" unless n > 0
  ... # other stuffs
end

There is require method in Scala which tests an expression, throwing an IllegalArgumentException if false.

if there is something acting like that in ruby?

I know ruby has assert series methods in unit test. But I don't think it is what I want.

EDITED

I just want to know if there are other ways to ensuring arguments meets some conditions, instead of raise.(The require in scala is so fit for that.)

Upvotes: 3

Views: 130

Answers (2)

Daniël Knippers
Daniël Knippers

Reputation: 3055

What's wrong with your initial try? It works fine if you indeed want to throw Exceptions. You can create a method to test the requirement if you want, but it does not really do much:

def req(cond, error)
  raise error if cond
end

def method(n)
  req(n < 0, ArgumentError.new('YOU BROKE IT'))
  # Method body
end

method(-1) # => method.rb:2:in 'req': YOU BROKE IT (ArgumentError)

Upvotes: 4

sawa
sawa

Reputation: 168219

If your problem is that you want to specify the error class, and want to write the condition to be satisfied rather than condition not to happen, then there is no special thing you need.

def some_method(n)
  raise ArgumentError.new("some error") unless some_condition
  raise ArgumentError.new("another error") unless another_condition
  raise ArgumentError.new("yet another error") unless yet_another_condition
  ...
end

Upvotes: 0

Related Questions