Re: Optional arguments and default values



Ross Bamford <rosco@xxxxxxxxxxxxxxxxxxxxxx> wrote:
On Fri, 30 Dec 2005 19:59:05 -0000, Surgeon <biyokuantum@xxxxxxxxx>
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

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.

Another solution would be to implement things like this in Enumerable:

module Enumerable
 def sum()     inject(0) {|a,b| a+b} end
 def product() inject(1) {|a,b| a*b} end
end

or

module Enumerable
 def sum()     inject {|a,b| a+b} end
 def product() inject {|a,b| a*b} end
end

Allowing for invocations like these

[1,2,3,4].sum
=> 10
(1..4).sum
=> 10
(1...5).sum
=> 10
(1..10).map { rand 20 }.sum
=> 91

Kind regards

   robert

.



Relevant Pages

  • Re: Optional arguments and default values
    ... foo is a function that multiplies all of its arguments together. ... def foo ... "qwerty" else ...
    (comp.lang.ruby)
  • Re: equivalent injecting implementations?
    ... def injecting ... implementation uses inject and takes a two argument block like inject ... Even if you do use it on an Array the two are not equivalent since the second variant does not propagate the block result. ...
    (comp.lang.ruby)
  • Re: [SUMMARY] Ducksay (#52)
    ... def width ... array on each pass, whereas the mapversion builds only one array. ... Even an inject() implementation without the arrays was running slower than the map() implementation on my computer. ...
    (comp.lang.ruby)
  • Re: Allow additional parameters to Enumerable#inject
    ... last_seen = elem ... I changed inject to take additional parameters: ... def inject_with_state ... memo, *other = yield ...
    (comp.lang.ruby)
  • Re: Modifying the first value with #inject
    ... def product ... inject{|total, entry| total - entry.to_f} ... respectively and the Numerics convert the arguments of +, ...
    (comp.lang.ruby)