如何重构此Ruby代码以检查有效参数?

时间:2012-11-23 19:18:17

标签: ruby exception error-handling refactoring

是否有更好(更有说服力)的方法来检查有效的参数?

def load_data filename, start_percent, end_percent
  raise 'Values must be [0,1]' if start_percent < 0
  raise 'Values must be [0,1]' if end_percent   < 0
  raise 'Values must be [0,1]' if start_percent > 1
  raise 'Values must be [0,1]' if end_percent   > 1
  ...

Ruby 1.9.3

编辑:start_percentend_percent应该是花车。

4 个答案:

答案 0 :(得分:2)

呀!取决于你只需要整数还是小数

# decimals
def load_data(filename, start_percent, end_percent)
  accepted = (0..1)
  unless accepted.cover? start_percent && accepted.cover? end_precent
    raise 'Values must be [0,1]'
  end
end

整数: 更改为accepted = [0,1]accepted.include? start_percent以及end_percent

参考文献:

范围#封面:http://ruby-doc.org/core-1.9.3/Range.html#method-i-cover-3F

范围#include?:http://ruby-doc.org/core-1.9.3/Range.html#method-i-include-3F

数组#include?:http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-include-3F

答案 1 :(得分:1)

紧凑版:

[start_percent, end_percent].each{|p| raise 'Values must be [0,1]' unless (0..1).cover?(p) }

答案 2 :(得分:1)

def load_data filename, start_percent, end_percent
  unless (0..1).include?(start_percent) and (0..1).include?(end_percent)
    raise 'Values must be [0,1]' 
  end
  ...

答案 3 :(得分:1)

发生此错误时,您需要知道详细信息(错误类型,参数,无效值):

def load_data filename, start_percent, end_percent
  raise ArgumentError, "start_percent must be [0,1]; received #{start_percent}." unless start_percent.between?(0, 1)
  raise ArgumentError, "end_percent must be [0,1]; received #{end_percent}." unless end_percent.between?(0, 1)
end