Re: Optional arguments and default values



On Sat, 31 Dec 2005 12:58:14 -0000, Robert Klemme <bob.news@xxxxxxx> wrote:

Ross Bamford <rosco@xxxxxxxxxxxxxxxxxxxxxx> wrote:
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

The implementation of Enumerable#inject allows for an even more elegant solution


def foo(*args)
  args.inject {|a,b| a*b} || "qwerty"
end

foo 2,3,5
=> 30
foo 2,3
=> 6
foo 2
=> 2
foo
=> "qwerty"

Note: if args is empty this inject returns nil, if there is just one element that is returned.


Cool, I didn't know that, thanks for pointing it out :)

Cheers,

--
Ross Bamford - rosco@xxxxxxxxxxxxxxxxxxxxxx
.