0

Is there a better (more eloquent) way to check for valid params?

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

EDIT: start_percent and end_percent are supposed to be floats.

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]とに変更accepted.include? start_percentend_percentます

参照:

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

Array#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
  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 に答える
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 に答える