On 24 February 2016 at 12:51, A Berger <aberger7890 / gmail.com> wrote:

> Hi
> can i "automagically" select a method by type or count of args?
> Meaning defining methods with same name (delegates?) doing differrent
> things if called differently [metaprogramming?]
> def xx(numeric x) x**2 end
> def xx(numeric x,y) x-2*y end
> def xx(string x) x+"xxx" end
> # can sg like  this be archived as valid  ruby input? type of method-args
> should be left out in defs, if can be derived from ops/return value of
> definition.
>
> Thank you
> Berg
>
Not the way you're writing it; but you can make #xx accept any oldargs,
and switch based on args count/types.

    def xx x, *rest
      case x
      when Numeric
        case rest.length
        when 0
          x ** 2 # or: xx_numeric(x)
        when 1
          x - 2 * rest.first # or: xx_numeric_any(x, *rest)
        else
          raise ArgumentError, "wrong number of arguments (#{rest.length}
for 1..2)"
        end
      when String
        x + "xxx" # or: xx_string(x)
      else
        raise ArgumentError, "wrong type of 'x': #{x.class}"
      end
    end

Although I'd usually advise against having one method do various
(arbitrary) things based on the parameters. It's usually better for each
method to have meaningful, consistent semantics. For example, I'd call your
first method #square and make it work as best I can for all possible values
of 'x'. And your last method I'd call something like #xcat (because it
conCATenates Xs) and let it work for any 'x'.

Also, you're going against the spirit of duck-typing. What if I make a
thing that looks and acts like a String, but doesn't extend String? Or
ditto Numeric?

Cheers
-- 
  Matthew Kerwin
  http://matthew.kerwin.net.au/
(supressed text/html)
Unsubscribe: <mailto:ruby-talk-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>