Mario Stoilov Mario Stoilov - 4 months ago 22
Ruby Question

Template methods in ruby

Simple question:

In java you can define :

void myFunction<T>(T value) { //do stuff }


Is there an equivalent in ruby, and if not, how can I achieve a similar result (passing class types?)

Answer

You can pass a class to a method just like passing normal objects. For example

def create_object(klass, *args)
  klass.new(*args)
end

create_object(String)  #=> ""
create_object(Hash)  #=> {}
create_object(Array, 3, :hello)  #=> [:hello, :hello, :hello]