0

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

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
  ...

红宝石 1.9.3

编辑:应该是花车start_percentend_percent

4

4 回答 4

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]andaccepted.include? start_percent和 for end_percenttoo

参考:

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

Range#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

于 2012-11-23T19:26:02.497 回答
1

紧凑版:

[start_percent, end_percent].each{|p| raise 'Values must be [0,1]' unless (0..1).cover?(p) }
于 2012-11-23T19:34:23.780 回答
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
  ...
于 2012-11-23T19:41:10.497 回答
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
于 2012-11-23T22:28:48.197 回答