Ruby中是否有一种优雅的方式,就像Scala中的`require`一样?

时间:2014-02-26 14:01:46

标签: ruby scala syntax

我想要做的是确保参数满足某些条件,否则会引发错误。

像这样(假设我想确保n> 0):

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

Scala中有require方法测试表达式,如果为false则抛出IllegalArgumentException。

如果在红宝石中有类似的东西吗?

我知道ruby在单元测试中有assert个系列方法。但我认为这不是我想要的。

EDITED

我只是想知道是否有其他方法可以确保参数符合某些条件,而不是raise。(scala中的require非常适合。)

2 个答案:

答案 0 :(得分:4)

您最初的尝试有什么问题?如果你确实想要抛出异常,它可以正常工作。如果需要,您可以创建一个测试需求的方法,但实际上并没有做太多的事情:

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)

答案 1 :(得分:0)

如果您的问题是您想要指定错误类,并且想要写条件以满足条件而不是条件不发生,那么您就没有特别需要。

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
相关问题