On Fri, 30 Dec 2005 19:59:05 -0000, Surgeon <biyokuantum / gmail.com> wrote:

> Hi,
>
> How do I give a method optional arguments and default values?
>
> Exmpl:
>
> foo is a function that multiplies all of its arguments together. If
> there is not any argument, a default value of "qwerty" returns.
>
> foo(2,3)    ---->  6
> foo(2,3,5) ----> 30
> foo(2,3,5,2) -> 60
>
> foo() -----------> "qwerty"
>

Maybe:
	def foo(*args)
	  args.empty? && "qwerty" or args.inject(0) { |s,i| s * i }
	end

or:

	def foo(*args)
	  if args.empty?
	    "qwerty"
	  else
	    args.inject(0) { |s,i| s * i }
	  end
	end

Default values are slightly different:

	def sum(v1 = 10, v2 = 5)
	  v1 + v2
	end

Once you give a default value to an arg, you must also give defaults to  
all following args (except any &block arg).

Defaults don't have to be literal - you can use anything

	def foo(arg = somemethod('c')) ... end

even another arg

	def foo(a1, a2 = a1) ... end

I believe they're evaluated in the scope of the method itself. It's quite  
cool.

Cheers,

-- 
Ross Bamford - rosco / roscopeco.remove.co.uk