我想知道在Ruby中调用了多少 return 参数method_missing。我想根据它应该产生多少返回参数来更改函数行为。我在Matlab中寻找相当于nargout
的东西。本例中的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
答案 0 :(得分: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 :(得分:0)
Ruby中没有多个返回值。方法总是返回一个值。从来没有。永远不会少。