--00151747b19a5ec8a004ab679c0a
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: quoted-printable

On Fri, Aug 26, 2011 at 12:52 PM, jack jones <shehio_22 / hotmail.com> wrote:

> def do_something(a as Array)
>  puts "first array method"
>  puts a.inspect
> end
>

This is not valid Ruby. Is your problem that you're getting a syntax
error? Are you giving faux-Ruby to demonstrate what you want? See below.


> # what's the problem here (A)?


Ruby is dynamically typed and there is no method overloading. Only the
method name distinguishes it from other methods, and you can't specify the
type of an argument in the way you're suggesting. You can fake method
overloading, by calling other methods:

def foo(x)
  foo_for_array(x) if x.is_a? Array
  foo_for_hash(x) if x.is_a? Hash
end

private

def foo_for_array(x)
  p "foo for array"
  p x.inspect
end

def foo_for_hash(x)
  p "foo for hash"
  p x.inspect
end

But don't do this. You'd be working against the language, instead of with
it, and you'd find yourself with more problems later down the line.

Instead of thinking of object types, follow duck typing[1] and think about
what an object is able to do, instead of what it is whether an object is
able to respond to a certain method call. In your particular case, it makes
no difference what the argument's class is, because they all respond to
#inspect:

def do_something(arg_of_any_class)
  puts arg_of_any_class.inspect
end

There's no need to try and restrict the type of arg_of_any_class.

[1] Duck typing: http://en.wikipedia.org/wiki/Duck_typing

--00151747b19a5ec8a004ab679c0a--