0

Ruby で method_missing が呼び出されている戻り引数の数を知りたいです。生成するはずの戻り引数の数に応じて、関数の動作を変更したいと思います。nargoutMatlabで同等のものを探しています。この例では XXX:

class Test
  def method_missing(method_id, *args)
    n_return_arguments = XXX
    if n_return_arguments == 1
      return 5
    else
      return 10, 20
    end
  end
end

t = Test.new.missing_method # t should now be 5

t1, t2 = Test.new.missing_method # t1 should now be 10 and t2 should now be 20
4

2 に答える 2

0

複数の引数がある場合、args変数は になります。Array返品を直接確認するだけです。配列の場合はサイズに応答し、そうでない場合は応答しない場合があります。クラスを使用するか、それを検査して、必要な情報を取得できます。

class Test
  def method_missing(method_id, *args)
    n_return_arguments = XXX
    if n_return_arguments == 1
      return 5
    else
      return 10, 20
    end
  end
end

XXX = "anything but 1"
t = Test.new.this_nonexistent_method # => 5
puts "t = #{t.inspect}"

XXX = 1
t1, t2 = Test.new.this_nonexistent_method.size # => 2
puts "t1 = #{t1.inspect}, t2 = #{t2.inspect}"

XXX 値を使用してメソッドの動作を変更します。

戻り値は常に 1 つの値であり、複数の要素を保持する配列の場合もあります。

于 2012-11-18T21:31:29.733 に答える