2

いくつかのルビ関数があり、入力が正しいことと、入力が意味をなすかどうかを確認したいと考えています。それを行うための賢明な方法は何ですか?

これは、私が持っている機能の1つと、確認したいものの例です

# Converts civil time to solar time
# civilT: Time object
# longitude: float
# timezone: fixnum
def to_solarT(civilT,longitude,timezone)
    # pseudo code to check that input is correct
    assert(civilT.class == Time.new(2013,1,1).class)
    assert(longitude.class == 8.0.class)
    assert(timezone.class == 1.class)

    # More pseudocode to check if the inputs makes sense, in this case 
    # whether the given longitude and timezone inputs make sense or whether 
    # the timezone relates to say Fiji and the longitude to Scotland. Done 
    # using the imaginary 'longitude_in_timezone' function
    assert(longitude_in_timezone(longitude,timezone))
end

ここで関連する質問を見つけました: how to put assertions in ruby​​ code。これは行くべき道ですか、それともルビーで関数入力をテストするためのより良い方法はありますか?

4

2 に答える 2

3

assertはRubyの標準的なメソッドではなく、テストフレームワークでよく使われるので、コードに入れるのは良くないと思います。また、引数をチェックしたいクラスのインスタンスを作成しても意味がありません。もっと簡単に言うと、

def to_solarT civilT, longitude, timezone
  raise "Argument error blah blah" unless Time === civilT
  raise "Argument error blah blah" unless Float === longitude
  raise "Argument error blah blah" unless Fixnum === timezone
  ...
end
于 2013-06-30T06:54:24.250 に答える
3

このようにしてはいけません。Ruby はダックタイピングに大きく依存しています。つまり、アヒルのように鳴くなら、それはアヒルです。つまり、受け取ったオブジェクトを使用するだけで、それらが正しく応答する場合は問題ありません。そうでない場合は、NoMethodError を救出し、適切な出力を表示できます。

于 2013-06-30T06:24:37.360 に答える