1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Soaking Method Arguments

By

2 of 2

Enforcing a Calling Convention

In methods that takes a variable amount of arguments, there's sometimes an informal calling convention. For instance, a soak operator must take 4 arguments, no more and no less unless it's empty. There's no way to tell Ruby this is what you really want, but you can integrate this nicely into your Ruby code by throwing the ArgumentError yourself.


#!/usr/bin/env ruby
def meth(a, *args)
 if args.length != 4 and not args.empty?
   raise ArgumentError, "args must be zero or four elements"
 end

 puts args.inspect
end

meth 1
# args is empty, this is OK

meth 1, 2,3,4,5
# args is four elements, this is OK

meth 1, 2
# args is 1 element, this will raise exception
  1. About.com
  2. Technology
  3. Ruby

©2014 About.com. All rights reserved.