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

What I want to do is make sure that the arguments satisfy some conditions, if not, errors occur.

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

Scala has a method requirethat checks an expression by throwing an IllegalArgumentException if false.

if the ruby โ€‹โ€‹has something like that?

I know that ruby โ€‹โ€‹has series methods assertin unit test. But I do not think that this is what I want.

EDITED

I just want to know if there are other ways to ensure that the arguments satisfy certain conditions, and not raise. ( requirein Scala is so suitable for this.)

+3
source share
2 answers

? , . , , :

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)
+4

, , , , , , , .

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
0

All Articles